@mcp-use/inspector 0.14.4-canary.0 → 0.14.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DnfVI-Ze.js","assets/index-VN9j3XIi.js","assets/index-BBY-cV7L.js","assets/llms-DQnVNuNk.js","assets/embeddings-BCZtnbP5.js","assets/index-Bt0sdCcf.js","assets/index-BmT6F6tU.js","assets/index-DqIRqeuh.js","assets/browser-CB208uLg.js"])))=>i.map(i=>d[i]);
2
- var XY=Object.defineProperty;var JY=(e,t,n)=>t in e?XY(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Og=(e,t,n)=>JY(e,typeof t!="symbol"?t+"":t,n);function QY(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const a in r)if(a!=="default"&&!(a in e)){const o=Object.getOwnPropertyDescriptor(r,a);o&&Object.defineProperty(e,a,o.get?o:{enumerable:!0,get:()=>r[a]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(a){if(a.ep)return;a.ep=!0;const o=n(a);fetch(a.href,o)}})();function Um(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function ITe(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function r(){var a=!1;try{a=this instanceof r}catch{}return a?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,a.get?a:{enumerable:!0,get:function(){return e[r]}})}),n}var qx={exports:{}},dp={};var Aj;function eZ(){if(Aj)return dp;Aj=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,a,o){var i=null;if(o!==void 0&&(i=""+o),a.key!==void 0&&(i=""+a.key),"key"in a){o={};for(var l in a)l!=="key"&&(o[l]=a[l])}else o=a;return a=o.ref,{$$typeof:e,type:r,key:i,ref:a!==void 0?a:null,props:o}}return dp.Fragment=t,dp.jsx=n,dp.jsxs=n,dp}var Ij;function tZ(){return Ij||(Ij=1,qx.exports=eZ()),qx.exports}var d=tZ();const nZ="modulepreload",rZ=function(e){return"/inspector/"+e},Oj={},Ua=function(t,n,r){let a=Promise.resolve();if(n&&n.length>0){let u=function(f){return Promise.all(f.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),l=i?.nonce||i?.getAttribute("nonce");a=u(n.map(f=>{if(f=rZ(f),f in Oj)return;Oj[f]=!0;const m=f.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":nZ,m||(g.as="script"),g.crossOrigin="",g.href=f,l&&g.setAttribute("nonce",l),document.head.appendChild(g),m)return new Promise((b,E)=>{g.addEventListener("load",b),g.addEventListener("error",()=>E(new Error(`Unable to preload CSS for ${f}`)))})}))}function o(i){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=i,window.dispatchEvent(l),!l.defaultPrevented)throw i}return a.then(i=>{for(const l of i||[])l.status==="rejected"&&o(l.reason);return t().catch(o)})};var aZ=Object.defineProperty,ze=(e,t)=>aZ(e,"name",{value:t,configurable:!0}),OTe=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});function o4(e){return e==="localhost"||e==="127.0.0.1"||e.startsWith("127.")||e.startsWith("192.168.")||e.startsWith("10.")||e.startsWith("172.")}ze(o4,"isLocalServer");function s4(e){const t=e.split(".");return t.length<=2?e:t.slice(t.length-2).join(".")}ze(s4,"getBaseDomain");function i4(e){return new Promise((t,n)=>{const r=new FileReader;r.onloadend=()=>{t(r.result)},r.onerror=n,r.readAsDataURL(e)})}ze(i4,"blobToBase64");async function l4(e){console.debug("[favicon-detector] Starting favicon detection for:",e);try{let t;if(e.startsWith("http://")||e.startsWith("https://")?t=new URL(e).hostname:e.includes("://")?t=e.split("://")[1].split("/")[0]:t=e.split("/")[0],console.debug("[favicon-detector] Extracted domain:",t),o4(t))return console.debug("[favicon-detector] Skipping local server:",t),null;const n=s4(t),r=t!==n?[t,n]:[t];console.debug("[favicon-detector] Domains to try:",r);for(const a of r)try{const o=`https://favicon.tools.mcp-use.com/${a}`;console.debug("[favicon-detector] Attempting to fetch favicon for:",a,"from:",o);const i=new AbortController,l=setTimeout(()=>i.abort(),2e3);try{const u=await fetch(o,{signal:i.signal});if(clearTimeout(l),!u.ok){console.debug("[favicon-detector] Fetch failed for",a,"with status:",u.status);continue}const f=await u.blob(),m=await i4(f);return console.debug("[favicon-detector] Successfully retrieved favicon for:",a,"size:",f.size,"bytes"),m}catch(u){clearTimeout(l),console.debug("[favicon-detector] Fetch error for",a,":",u instanceof Error?u.message:String(u));continue}}catch(o){console.debug("[favicon-detector] Error processing domain",a,":",o instanceof Error?o.message:String(o));continue}return console.debug("[favicon-detector] All attempts failed for:",e),null}catch(t){return console.warn("[favicon-detector] Error detecting favicon:",t),null}}ze(l4,"detectFavicon");function c4(e,t){const n=t?.headers??t?.customHeaders??{};if(t?.customHeaders&&!t?.headers&&console.warn('[applyProxyConfig] The "customHeaders" option in proxyConfig is deprecated. Use "headers" instead.'),!t?.proxyAddress)return{url:e,headers:n};const r=new URL(t.proxyAddress),a=new URL(e),o=`${r.origin}${r.pathname}${a.pathname}${a.search}`,i={"X-Target-URL":e,...n};return{url:o,headers:i}}ze(c4,"applyProxyConfig");var xp={},u4="mcp-use";function TS(e){switch((typeof process<"u"&&xp?e:void 0)?.trim()){case"2":return"debug";case"1":return"info";default:return"info"}}ze(TS,"resolveLevel");function d4(e){return e.length===0?"":e.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ")}ze(d4,"formatArgs");var sd,oZ=(sd=class{_level;name;format;constructor(t=u4,n="info",r="minimal"){this.name=t,this._level=n,this.format=r}shouldLog(t){const n=["error","warn","info","http","verbose","debug","silly"],r=n.indexOf(this._level);return n.indexOf(t)<=r}formatMessage(t,n,r){const a=new Date().toLocaleTimeString("en-US",{hour12:!1}),o=d4(r),i=o?`${n} ${o}`:n;switch(this.format){case"detailed":return`${a} [${this.name}] ${t.toUpperCase()}: ${i}`;case"emoji":{const l={error:"❌",warn:"⚠️",info:"ℹ️",http:"🌐",verbose:"📝",debug:"🔍",silly:"🤪"};return`${a} [${this.name}] ${l[t]||""} ${t.toUpperCase()}: ${i}`}case"minimal":default:return`${a} [${this.name}] ${t}: ${i}`}}error(t,...n){this.shouldLog("error")&&console.error(this.formatMessage("error",t,n))}warn(t,...n){this.shouldLog("warn")&&console.warn(this.formatMessage("warn",t,n))}info(t,...n){this.shouldLog("info")&&console.info(this.formatMessage("info",t,n))}debug(t,...n){this.shouldLog("debug")&&console.debug(this.formatMessage("debug",t,n))}http(t,...n){this.shouldLog("http")&&console.log(this.formatMessage("http",t,n))}verbose(t,...n){this.shouldLog("verbose")&&console.log(this.formatMessage("verbose",t,n))}silly(t,...n){this.shouldLog("silly")&&console.log(this.formatMessage("silly",t,n))}get level(){return this._level}set level(t){this._level=t}setFormat(t){this.format=t}},ze(sd,"SimpleConsoleLogger"),sd),Zi,sZ=(Zi=class{static get(t=u4){if(!this.instances[t]){const n=typeof process<"u"&&xp?.DEBUG||void 0;this.instances[t]=new oZ(t,TS(n),this.currentFormat)}return this.instances[t]}static configure(t={}){const{level:n,format:r="minimal"}=t,a=typeof process<"u"&&xp?.DEBUG||void 0,o=n??TS(a);this.currentFormat=r,Object.values(this.instances).forEach(i=>{i.level=o,i.setFormat(r)})}static setDebug(t){let n;t===2||t===!0?n="debug":n="info",Object.values(this.instances).forEach(r=>{r.level=n}),typeof process<"u"&&xp&&(xp.DEBUG=t?t===!0?"2":String(t):"0")}static setFormat(t){this.currentFormat=t,this.configure({format:t})}},ze(Zi,"Logger"),Og(Zi,"instances",{}),Og(Zi,"currentFormat","minimal"),Zi),Fe=sZ.get(),iZ="1.12.4-canary.0";function Sv(){return iZ}ze(Sv,"getPackageVersion");var id,Yo=(id=class{},ze(id,"BaseTelemetryEvent"),id),ld,lZ=(ld=class extends Yo{constructor(t){super(),this.data=t}get name(){return"mcp_agent_execution"}get properties(){return{execution_method:this.data.executionMethod,query:this.data.query,query_length:this.data.query.length,success:this.data.success,model_provider:this.data.modelProvider,model_name:this.data.modelName,server_count:this.data.serverCount,server_identifiers:this.data.serverIdentifiers,total_tools_available:this.data.totalToolsAvailable,tools_available_names:this.data.toolsAvailableNames,max_steps_configured:this.data.maxStepsConfigured,memory_enabled:this.data.memoryEnabled,use_server_manager:this.data.useServerManager,max_steps_used:this.data.maxStepsUsed,manage_connector:this.data.manageConnector,external_history_used:this.data.externalHistoryUsed,steps_taken:this.data.stepsTaken??null,tools_used_count:this.data.toolsUsedCount??null,tools_used_names:this.data.toolsUsedNames??null,response:this.data.response??null,response_length:this.data.response?this.data.response.length:null,execution_time_ms:this.data.executionTimeMs??null,error_type:this.data.errorType??null,conversation_history_length:this.data.conversationHistoryLength??null}}},ze(ld,"MCPAgentExecutionEvent"),ld);function f4(e,t){const n=Array.from(e.registrations.tools.values()),r=Array.from(e.registrations.prompts.values()),a=Array.from(e.registrations.resources.values()),o=Array.from(e.registrations.resourceTemplates.values()),i=a.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,uri:m.config.uri??null,mime_type:m.config.mimeType??null})),l=i.filter(m=>m.mime_type==="text/html+skybridge"),u=i.filter(m=>m.mime_type==="text/uri-list"||m.mime_type==="text/html"),f=i.filter(m=>m.mime_type==="text/html+mcp");return{transport:t,toolsNumber:e.registeredTools.length,resourcesNumber:e.registeredResources.length,promptsNumber:e.registeredPrompts.length,auth:!!e.oauthProvider,name:e.config.name,description:e.config.description??null,baseUrl:e.serverBaseUrl??null,toolNames:e.registeredTools.length>0?e.registeredTools:null,resourceNames:e.registeredResources.length>0?e.registeredResources:null,promptNames:e.registeredPrompts.length>0?e.registeredPrompts:null,tools:n.length>0?n.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,input_schema:m.config.schema?JSON.stringify(m.config.schema):null,output_schema:m.config.outputSchema?JSON.stringify(m.config.outputSchema):null})):null,resources:i.length>0?i:null,prompts:r.length>0?r.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,args:m.config.args?JSON.stringify(m.config.args):null})):null,templates:o.length>0?o.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null})):null,capabilities:{logging:!0,resources:{subscribe:!0,listChanged:!0}},appsSdkResources:l.length>0?l:null,appsSdkResourcesNumber:l.length,mcpUiResources:u.length>0?u:null,mcpUiResourcesNumber:u.length,mcpAppsResources:f.length>0?f:null,mcpAppsResourcesNumber:f.length}}ze(f4,"createServerRunEventData");var cd,cZ=(cd=class extends Yo{constructor(t){super(),this.data=t}get name(){return"server_run"}get properties(){return{transport:this.data.transport,tools_number:this.data.toolsNumber,resources_number:this.data.resourcesNumber,prompts_number:this.data.promptsNumber,auth:this.data.auth,name:this.data.name,description:this.data.description??null,base_url:this.data.baseUrl??null,tool_names:this.data.toolNames??null,resource_names:this.data.resourceNames??null,prompt_names:this.data.promptNames??null,tools:this.data.tools??null,resources:this.data.resources??null,prompts:this.data.prompts??null,templates:this.data.templates??null,capabilities:this.data.capabilities?JSON.stringify(this.data.capabilities):null,apps_sdk_resources:this.data.appsSdkResources?JSON.stringify(this.data.appsSdkResources):null,apps_sdk_resources_number:this.data.appsSdkResourcesNumber??0,mcp_ui_resources:this.data.mcpUiResources?JSON.stringify(this.data.mcpUiResources):null,mcp_ui_resources_number:this.data.mcpUiResourcesNumber??0,mcp_apps_resources:this.data.mcpAppsResources?JSON.stringify(this.data.mcpAppsResources):null,mcp_apps_resources_number:this.data.mcpAppsResourcesNumber??0}}},ze(cd,"ServerRunEvent"),cd),ud,uZ=(ud=class extends Yo{constructor(t){super(),this.data=t}get name(){return"server_initialize_call"}get properties(){return{protocol_version:this.data.protocolVersion,client_info:JSON.stringify(this.data.clientInfo),client_capabilities:JSON.stringify(this.data.clientCapabilities),session_id:this.data.sessionId??null}}},ze(ud,"ServerInitializeEvent"),ud),dd,dZ=(dd=class extends Yo{constructor(t){super(),this.data=t}get name(){return"server_tool_call"}get properties(){return{tool_name:this.data.toolName,length_input_argument:this.data.lengthInputArgument,success:this.data.success,error_type:this.data.errorType??null,execution_time_ms:this.data.executionTimeMs??null}}},ze(dd,"ServerToolCallEvent"),dd),fd,fZ=(fd=class extends Yo{constructor(t){super(),this.data=t}get name(){return"server_resource_call"}get properties(){return{name:this.data.name,description:this.data.description,contents:this.data.contents,success:this.data.success,error_type:this.data.errorType??null}}},ze(fd,"ServerResourceCallEvent"),fd),pd,pZ=(pd=class extends Yo{constructor(t){super(),this.data=t}get name(){return"server_prompt_call"}get properties(){return{name:this.data.name,description:this.data.description,success:this.data.success,error_type:this.data.errorType??null}}},ze(pd,"ServerPromptCallEvent"),pd),md,mZ=(md=class extends Yo{constructor(t){super(),this.data=t}get name(){return`server_context_${this.data.contextType}`}get properties(){return{context_type:this.data.contextType,notification_type:this.data.notificationType??null}}},ze(md,"ServerContextEvent"),md),hd,hZ=(hd=class extends Yo{constructor(t){super(),this.data=t}get name(){return"mcpclient_init"}get properties(){return{code_mode:this.data.codeMode,sandbox:this.data.sandbox,all_callbacks:this.data.allCallbacks,verify:this.data.verify,servers:this.data.servers,num_servers:this.data.numServers,is_browser:this.data.isBrowser}}},ze(hd,"MCPClientInitEvent"),hd),gd,gZ=(gd=class extends Yo{constructor(t){super(),this.data=t}get name(){return"connector_init"}get properties(){return{connector_type:this.data.connectorType,server_command:this.data.serverCommand??null,server_args:this.data.serverArgs??null,server_url:this.data.serverUrl??null,public_identifier:this.data.publicIdentifier??null}}},ze(gd,"ConnectorInitEvent"),gd),bd,bZ=(bd=class extends Yo{constructor(t){super(),this.data=t}get name(){return"client_add_server"}get properties(){const{serverName:t,serverConfig:n}=this.data,r=n.url;return{server_name:t,server_url_domain:r?this._extractHostname(r):null,transport:n.transport??null,has_auth:!!(n.authToken||n.authProvider)}}_extractHostname(t){try{return new URL(t).hostname}catch{return null}}},ze(bd,"ClientAddServerEvent"),bd),yd,yZ=(yd=class extends Yo{constructor(t){super(),this.data=t}get name(){return"client_remove_server"}get properties(){return{server_name:this.data.serverName}}},ze(yd,"ClientRemoveServerEvent"),yd);function p4(e){return e._llm_type||e.constructor.name.toLowerCase()}ze(p4,"getModelProvider");function m4(e){if("_identifyingParams"in e){const t=e._identifyingParams;if(typeof t=="object"&&t!==null){for(const n of["model","modelName","model_name","modelId","model_id","deploymentName","deployment_name"])if(n in t)return String(t[n])}}return e.model||e.modelName||e.constructor.name}ze(m4,"getModelName");function vZ(e){return[p4(e),m4(e)]}ze(vZ,"extractModelInfo");function Yb(){if(typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();if(typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.getRandomValues=="function"){const e=new Uint8Array(16);globalThis.crypto.getRandomValues(e);const t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.substring(0,8)}-${t.substring(8,12)}-${t.substring(12,16)}-${t.substring(16,20)}-${t.substring(20)}`}return`${Date.now()}-${Math.random().toString(36).substring(2,15)}-${Math.random().toString(36).substring(2,15)}`}ze(Yb,"generateUUID");function Zb(){if(typeof window<"u"&&window.crypto&&typeof window.crypto.getRandomValues=="function"){const e=new Uint8Array(8);return window.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}if(typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.getRandomValues=="function"){const e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}return Math.random().toString(36).substring(2,15)}ze(Zb,"secureRandomString");var Dj="mcp_use_user_id";function h4(){try{return typeof window<"u"&&typeof document<"u"?"browser":"unknown"}catch{return"unknown"}}ze(h4,"detectRuntimeEnvironment");function g4(e){if(e==="browser")try{if(typeof localStorage<"u")return localStorage.setItem("__mcp_use_test__","1"),localStorage.removeItem("__mcp_use_test__"),"localStorage"}catch{}return"session-only"}ze(g4,"getStorageCapability");var Xx=null;function b4(){return Xx===null&&(Xx=h4()),Xx}ze(b4,"getRuntimeEnvironment");var Fo,y4=(Fo=class{PROJECT_API_KEY="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";HOST="https://eu.i.posthog.com";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogBrowserClient=null;_posthogLoading=null;_runtimeEnvironment;_storageCapability;_source;constructor(){this._runtimeEnvironment=b4(),this._storageCapability=g4(this._runtimeEnvironment),this._source=this._getSourceFromLocalStorage()||this._runtimeEnvironment;const t=this._checkTelemetryDisabled(),n=this._runtimeEnvironment!=="unknown";t?(this._posthogBrowserClient=null,Fe.debug("Telemetry disabled via localStorage")):n?(Fe.info("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false in localStorage to disable."),this._posthogLoading=this._initPostHogBrowser()):(this._posthogBrowserClient=null,Fe.debug(`Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`))}_getSourceFromLocalStorage(){try{if(typeof localStorage<"u")return localStorage.getItem("MCP_USE_TELEMETRY_SOURCE")}catch{}return null}_checkTelemetryDisabled(){return typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}async _initPostHogBrowser(){try{const n=await Ua(()=>import("./module-D4IOASh4.js"),[]),r=n.default||n.posthog;if(!r||typeof r.init!="function")throw new Error("posthog-js module did not export expected interface");r.init(this.PROJECT_API_KEY,{api_host:this.HOST,persistence:"localStorage",autocapture:!1,capture_pageview:!1,disable_session_recording:!0,loaded:ze(()=>{Fe.debug("PostHog browser client initialized")},"loaded")}),this._posthogBrowserClient=r}catch(t){Fe.warn(`Failed to initialize PostHog browser telemetry: ${t}`),this._posthogBrowserClient=null}}get runtimeEnvironment(){return this._runtimeEnvironment}get storageCapability(){return this._storageCapability}static getInstance(){return Fo.instance||(Fo.instance=new Fo),Fo.instance}setSource(t){this._source=t;try{typeof localStorage<"u"&&localStorage.setItem("MCP_USE_TELEMETRY_SOURCE",t)}catch{}Fe.debug(`Telemetry source set to: ${t}`)}getSource(){return this._source}get isEnabled(){return this._posthogBrowserClient!==null}get userId(){if(this._currUserId)return this._currUserId;try{switch(this._storageCapability){case"localStorage":this._currUserId=this._getUserIdFromLocalStorage();break;case"session-only":default:try{this._currUserId=`session-${Yb()}`}catch{this._currUserId=`session-${Date.now()}-${Zb()}`}break}}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}_getUserIdFromLocalStorage(){try{if(typeof localStorage>"u")throw new Error("localStorage is not available");try{localStorage.setItem("__mcp_use_test__","1"),localStorage.removeItem("__mcp_use_test__")}catch(n){throw new Error(`localStorage is not writable: ${n}`)}let t=localStorage.getItem(Dj);if(!t){try{t=Yb()}catch{t=`${Date.now()}-${Zb()}`}localStorage.setItem(Dj,t)}return t}catch(t){Fe.debug(`Failed to access localStorage for user ID: ${t}`);let n;try{n=`session-${Yb()}`}catch{n=`session-${Date.now()}-${Zb()}`}return n}}async capture(t){if(this._posthogLoading&&await this._posthogLoading,!this._posthogBrowserClient)return;const n=this.userId,r={...t.properties};if(r.mcp_use_version=Sv(),r.language="typescript",r.source=this._source,r.runtime=this._runtimeEnvironment,this._posthogBrowserClient)try{this._posthogBrowserClient.capture(t.name,{...r,distinct_id:n})}catch(a){Fe.debug(`Failed to track PostHog Browser event ${t.name}: ${a}`)}}async trackAgentExecution(t){if(!this.isEnabled)return;const n=new lZ(t);await this.capture(n)}async trackServerRunFromServer(t,n){if(!this.isEnabled)return;const r=f4(t,n),a=new cZ(r);await this.capture(a)}async trackServerInitialize(t){if(!this.isEnabled)return;const n=new uZ(t);await this.capture(n)}async trackServerToolCall(t){if(!this.isEnabled)return;const n=new dZ(t);await this.capture(n)}async trackServerResourceCall(t){if(!this.isEnabled)return;const n=new fZ(t);await this.capture(n)}async trackServerPromptCall(t){if(!this.isEnabled)return;const n=new pZ(t);await this.capture(n)}async trackServerContext(t){if(!this.isEnabled)return;const n=new mZ(t);await this.capture(n)}async trackMCPClientInit(t){if(!this.isEnabled)return;const n=new hZ(t);await this.capture(n)}async trackConnectorInit(t){if(!this.isEnabled)return;const n=new gZ(t);await this.capture(n)}async trackClientAddServer(t,n){if(!this.isEnabled)return;const r=new bZ({serverName:t,serverConfig:n});await this.capture(r)}async trackClientRemoveServer(t){if(!this.isEnabled)return;const n=new yZ({serverName:t});await this.capture(n)}async trackUseMcpConnection(t){this.isEnabled&&await this.capture({name:"usemcp_connection",properties:{url_domain:new URL(t.url).hostname,transport_type:t.transportType,success:t.success,error_type:t.errorType??null,connection_time_ms:t.connectionTimeMs??null,has_oauth:t.hasOAuth,has_sampling:t.hasSampling,has_elicitation:t.hasElicitation}})}async trackUseMcpToolCall(t){this.isEnabled&&await this.capture({name:"usemcp_tool_call",properties:{tool_name:t.toolName,success:t.success,error_type:t.errorType??null,execution_time_ms:t.executionTimeMs??null}})}async trackUseMcpResourceRead(t){this.isEnabled&&await this.capture({name:"usemcp_resource_read",properties:{resource_uri_scheme:t.resourceUri.split(":")[0],success:t.success,error_type:t.errorType??null}})}identify(t,n){if(this._posthogBrowserClient)try{this._posthogBrowserClient.identify(t,n)}catch(r){Fe.debug(`Failed to identify user: ${r}`)}}reset(){if(this._posthogBrowserClient)try{this._posthogBrowserClient.reset()}catch(t){Fe.debug(`Failed to reset user: ${t}`)}this._currUserId=null}flush(){}shutdown(){}async trackPackageDownload(t){}},ze(Fo,"Telemetry"),Og(Fo,"instance",null),Fo),rs=y4;function wZ(e){rs.getInstance().setSource(e)}ze(wZ,"setTelemetrySource");const xZ=Object.freeze({status:"aborted"});function Oe(e,t,n){function r(l,u){if(l._zod||Object.defineProperty(l,"_zod",{value:{def:u,constr:i,traits:new Set},enumerable:!1}),l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,u);const f=i.prototype,m=Object.keys(f);for(let h=0;h<m.length;h++){const g=m[h];g in l||(l[g]=f[g].bind(l))}}const a=n?.Parent??Object;class o extends a{}Object.defineProperty(o,"name",{value:e});function i(l){var u;const f=n?.Parent?new o:this;r(f,l),(u=f._zod).deferred??(u.deferred=[]);for(const m of f._zod.deferred)m();return f}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Ku extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class v4 extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const NS={};function ol(e){return e&&Object.assign(NS,e),NS}function w4(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,a])=>t.indexOf(+r)===-1).map(([r,a])=>a)}function DTe(e,t="|"){return e.map(n=>NZ(n)).join(t)}function CS(e,t){return typeof t=="bigint"?t.toString():t}function _v(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function FT(e){return e==null}function BT(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function EZ(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let a=(r.split(".")[1]||"").length;if(a===0&&/\d?e-\d?/.test(r)){const u=r.match(/\d?e-(\d?)/);u?.[1]&&(a=Number.parseInt(u[1]))}const o=n>a?n:a,i=Number.parseInt(e.toFixed(o).replace(".","")),l=Number.parseInt(t.toFixed(o).replace(".",""));return i%l/10**o}const Lj=Symbol("evaluating");function Vn(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Lj)return r===void 0&&(r=Lj,r=n()),r},set(a){Object.defineProperty(e,t,{value:a})},configurable:!0})}function wc(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function xc(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function Mj(e){return JSON.stringify(e)}function SZ(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const x4="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Qp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const _Z=_v(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Ad(e){if(Qp(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Qp(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function E4(e){return Ad(e)?{...e}:Array.isArray(e)?[...e]:e}const TZ=new Set(["string","number","symbol"]);function Id(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pl(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function yt(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function NZ(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function CZ(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const RZ={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function kZ(e,t){const n=e._zod.def,r=xc(e._zod.def,{get shape(){const a={};for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(a[o]=n.shape[o])}return wc(this,"shape",a),a},checks:[]});return pl(e,r)}function AZ(e,t){const n=e._zod.def,r=xc(e._zod.def,{get shape(){const a={...e._zod.def.shape};for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete a[o]}return wc(this,"shape",a),a},checks:[]});return pl(e,r)}function IZ(e,t){if(!Ad(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const a=xc(e._zod.def,{get shape(){const o={...e._zod.def.shape,...t};return wc(this,"shape",o),o},checks:[]});return pl(e,a)}function OZ(e,t){if(!Ad(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return wc(this,"shape",r),r},checks:e._zod.def.checks};return pl(e,n)}function DZ(e,t){const n=xc(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return wc(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]});return pl(e,n)}function LZ(e,t,n){const r=xc(t._zod.def,{get shape(){const a=t._zod.def.shape,o={...a};if(n)for(const i in n){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(o[i]=e?new e({type:"optional",innerType:a[i]}):a[i])}else for(const i in a)o[i]=e?new e({type:"optional",innerType:a[i]}):a[i];return wc(this,"shape",o),o},checks:[]});return pl(t,r)}function MZ(e,t,n){const r=xc(t._zod.def,{get shape(){const a=t._zod.def.shape,o={...a};if(n)for(const i in n){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(o[i]=new e({type:"nonoptional",innerType:a[i]}))}else for(const i in a)o[i]=new e({type:"nonoptional",innerType:a[i]});return wc(this,"shape",o),o},checks:[]});return pl(t,r)}function Au(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Jl(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Dg(e){return typeof e=="string"?e:e?.message}function sl(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const a=Dg(e.inst?._zod.def?.error?.(e))??Dg(t?.error?.(e))??Dg(n.customError?.(e))??Dg(n.localeError?.(e))??"Invalid input";r.message=a}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function HT(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function em(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const S4=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,CS,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},_4=Oe("$ZodError",S4),Tv=Oe("$ZodError",S4,{Parent:Error});function jZ(e,t=n=>n.message){const n={},r=[];for(const a of e.issues)a.path.length>0?(n[a.path[0]]=n[a.path[0]]||[],n[a.path[0]].push(t(a))):r.push(t(a));return{formErrors:r,fieldErrors:n}}function PZ(e,t=n=>n.message){const n={_errors:[]},r=a=>{for(const o of a.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(i=>r({issues:i}));else if(o.code==="invalid_key")r({issues:o.issues});else if(o.code==="invalid_element")r({issues:o.issues});else if(o.path.length===0)n._errors.push(t(o));else{let i=n,l=0;for(;l<o.path.length;){const u=o.path[l];l===o.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(t(o))):i[u]=i[u]||{_errors:[]},i=i[u],l++}}};return r(e),n}function $Z(e){const t=[],n=e.map(r=>typeof r=="object"?r.key:r);for(const r of n)typeof r=="number"?t.push(`[${r}]`):typeof r=="symbol"?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function LTe(e){const t=[],n=[...e.issues].sort((r,a)=>(r.path??[]).length-(a.path??[]).length);for(const r of n)t.push(`✖ ${r.message}`),r.path?.length&&t.push(` → at ${$Z(r.path)}`);return t.join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CR746V6H.js","assets/index-Bx2mJviJ.js","assets/index-Bs_zxOrk.js","assets/llms-Cqeyha1C.js","assets/embeddings-Doip16mQ.js","assets/index-VvYXvWPp.js","assets/index-C6J4X9FC.js","assets/index-BVVKUeFG.js","assets/browser-jWg_baZz.js"])))=>i.map(i=>d[i]);
2
+ var XY=Object.defineProperty;var JY=(e,t,n)=>t in e?XY(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Og=(e,t,n)=>JY(e,typeof t!="symbol"?t+"":t,n);function QY(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const a in r)if(a!=="default"&&!(a in e)){const o=Object.getOwnPropertyDescriptor(r,a);o&&Object.defineProperty(e,a,o.get?o:{enumerable:!0,get:()=>r[a]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(a){if(a.ep)return;a.ep=!0;const o=n(a);fetch(a.href,o)}})();function Um(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function ITe(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function r(){var a=!1;try{a=this instanceof r}catch{}return a?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,a.get?a:{enumerable:!0,get:function(){return e[r]}})}),n}var qx={exports:{}},dp={};var Aj;function eZ(){if(Aj)return dp;Aj=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,a,o){var i=null;if(o!==void 0&&(i=""+o),a.key!==void 0&&(i=""+a.key),"key"in a){o={};for(var l in a)l!=="key"&&(o[l]=a[l])}else o=a;return a=o.ref,{$$typeof:e,type:r,key:i,ref:a!==void 0?a:null,props:o}}return dp.Fragment=t,dp.jsx=n,dp.jsxs=n,dp}var Ij;function tZ(){return Ij||(Ij=1,qx.exports=eZ()),qx.exports}var d=tZ();const nZ="modulepreload",rZ=function(e){return"/inspector/"+e},Oj={},Ua=function(t,n,r){let a=Promise.resolve();if(n&&n.length>0){let u=function(f){return Promise.all(f.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),l=i?.nonce||i?.getAttribute("nonce");a=u(n.map(f=>{if(f=rZ(f),f in Oj)return;Oj[f]=!0;const m=f.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":nZ,m||(g.as="script"),g.crossOrigin="",g.href=f,l&&g.setAttribute("nonce",l),document.head.appendChild(g),m)return new Promise((b,E)=>{g.addEventListener("load",b),g.addEventListener("error",()=>E(new Error(`Unable to preload CSS for ${f}`)))})}))}function o(i){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=i,window.dispatchEvent(l),!l.defaultPrevented)throw i}return a.then(i=>{for(const l of i||[])l.status==="rejected"&&o(l.reason);return t().catch(o)})};var aZ=Object.defineProperty,ze=(e,t)=>aZ(e,"name",{value:t,configurable:!0}),OTe=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});function o4(e){return e==="localhost"||e==="127.0.0.1"||e.startsWith("127.")||e.startsWith("192.168.")||e.startsWith("10.")||e.startsWith("172.")}ze(o4,"isLocalServer");function s4(e){const t=e.split(".");return t.length<=2?e:t.slice(t.length-2).join(".")}ze(s4,"getBaseDomain");function i4(e){return new Promise((t,n)=>{const r=new FileReader;r.onloadend=()=>{t(r.result)},r.onerror=n,r.readAsDataURL(e)})}ze(i4,"blobToBase64");async function l4(e){console.debug("[favicon-detector] Starting favicon detection for:",e);try{let t;if(e.startsWith("http://")||e.startsWith("https://")?t=new URL(e).hostname:e.includes("://")?t=e.split("://")[1].split("/")[0]:t=e.split("/")[0],console.debug("[favicon-detector] Extracted domain:",t),o4(t))return console.debug("[favicon-detector] Skipping local server:",t),null;const n=s4(t),r=t!==n?[t,n]:[t];console.debug("[favicon-detector] Domains to try:",r);for(const a of r)try{const o=`https://favicon.tools.mcp-use.com/${a}`;console.debug("[favicon-detector] Attempting to fetch favicon for:",a,"from:",o);const i=new AbortController,l=setTimeout(()=>i.abort(),2e3);try{const u=await fetch(o,{signal:i.signal});if(clearTimeout(l),!u.ok){console.debug("[favicon-detector] Fetch failed for",a,"with status:",u.status);continue}const f=await u.blob(),m=await i4(f);return console.debug("[favicon-detector] Successfully retrieved favicon for:",a,"size:",f.size,"bytes"),m}catch(u){clearTimeout(l),console.debug("[favicon-detector] Fetch error for",a,":",u instanceof Error?u.message:String(u));continue}}catch(o){console.debug("[favicon-detector] Error processing domain",a,":",o instanceof Error?o.message:String(o));continue}return console.debug("[favicon-detector] All attempts failed for:",e),null}catch(t){return console.warn("[favicon-detector] Error detecting favicon:",t),null}}ze(l4,"detectFavicon");function c4(e,t){const n=t?.headers??t?.customHeaders??{};if(t?.customHeaders&&!t?.headers&&console.warn('[applyProxyConfig] The "customHeaders" option in proxyConfig is deprecated. Use "headers" instead.'),!t?.proxyAddress)return{url:e,headers:n};const r=new URL(t.proxyAddress),a=new URL(e),o=`${r.origin}${r.pathname}${a.pathname}${a.search}`,i={"X-Target-URL":e,...n};return{url:o,headers:i}}ze(c4,"applyProxyConfig");var xp={},u4="mcp-use";function TS(e){switch((typeof process<"u"&&xp?e:void 0)?.trim()){case"2":return"debug";case"1":return"info";default:return"info"}}ze(TS,"resolveLevel");function d4(e){return e.length===0?"":e.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}).join(" ")}ze(d4,"formatArgs");var sd,oZ=(sd=class{_level;name;format;constructor(t=u4,n="info",r="minimal"){this.name=t,this._level=n,this.format=r}shouldLog(t){const n=["error","warn","info","http","verbose","debug","silly"],r=n.indexOf(this._level);return n.indexOf(t)<=r}formatMessage(t,n,r){const a=new Date().toLocaleTimeString("en-US",{hour12:!1}),o=d4(r),i=o?`${n} ${o}`:n;switch(this.format){case"detailed":return`${a} [${this.name}] ${t.toUpperCase()}: ${i}`;case"emoji":{const l={error:"❌",warn:"⚠️",info:"ℹ️",http:"🌐",verbose:"📝",debug:"🔍",silly:"🤪"};return`${a} [${this.name}] ${l[t]||""} ${t.toUpperCase()}: ${i}`}case"minimal":default:return`${a} [${this.name}] ${t}: ${i}`}}error(t,...n){this.shouldLog("error")&&console.error(this.formatMessage("error",t,n))}warn(t,...n){this.shouldLog("warn")&&console.warn(this.formatMessage("warn",t,n))}info(t,...n){this.shouldLog("info")&&console.info(this.formatMessage("info",t,n))}debug(t,...n){this.shouldLog("debug")&&console.debug(this.formatMessage("debug",t,n))}http(t,...n){this.shouldLog("http")&&console.log(this.formatMessage("http",t,n))}verbose(t,...n){this.shouldLog("verbose")&&console.log(this.formatMessage("verbose",t,n))}silly(t,...n){this.shouldLog("silly")&&console.log(this.formatMessage("silly",t,n))}get level(){return this._level}set level(t){this._level=t}setFormat(t){this.format=t}},ze(sd,"SimpleConsoleLogger"),sd),Zi,sZ=(Zi=class{static get(t=u4){if(!this.instances[t]){const n=typeof process<"u"&&xp?.DEBUG||void 0;this.instances[t]=new oZ(t,TS(n),this.currentFormat)}return this.instances[t]}static configure(t={}){const{level:n,format:r="minimal"}=t,a=typeof process<"u"&&xp?.DEBUG||void 0,o=n??TS(a);this.currentFormat=r,Object.values(this.instances).forEach(i=>{i.level=o,i.setFormat(r)})}static setDebug(t){let n;t===2||t===!0?n="debug":n="info",Object.values(this.instances).forEach(r=>{r.level=n}),typeof process<"u"&&xp&&(xp.DEBUG=t?t===!0?"2":String(t):"0")}static setFormat(t){this.currentFormat=t,this.configure({format:t})}},ze(Zi,"Logger"),Og(Zi,"instances",{}),Og(Zi,"currentFormat","minimal"),Zi),Fe=sZ.get(),iZ="1.12.4";function Sv(){return iZ}ze(Sv,"getPackageVersion");var id,Yo=(id=class{},ze(id,"BaseTelemetryEvent"),id),ld,lZ=(ld=class extends Yo{constructor(t){super(),this.data=t}get name(){return"mcp_agent_execution"}get properties(){return{execution_method:this.data.executionMethod,query:this.data.query,query_length:this.data.query.length,success:this.data.success,model_provider:this.data.modelProvider,model_name:this.data.modelName,server_count:this.data.serverCount,server_identifiers:this.data.serverIdentifiers,total_tools_available:this.data.totalToolsAvailable,tools_available_names:this.data.toolsAvailableNames,max_steps_configured:this.data.maxStepsConfigured,memory_enabled:this.data.memoryEnabled,use_server_manager:this.data.useServerManager,max_steps_used:this.data.maxStepsUsed,manage_connector:this.data.manageConnector,external_history_used:this.data.externalHistoryUsed,steps_taken:this.data.stepsTaken??null,tools_used_count:this.data.toolsUsedCount??null,tools_used_names:this.data.toolsUsedNames??null,response:this.data.response??null,response_length:this.data.response?this.data.response.length:null,execution_time_ms:this.data.executionTimeMs??null,error_type:this.data.errorType??null,conversation_history_length:this.data.conversationHistoryLength??null}}},ze(ld,"MCPAgentExecutionEvent"),ld);function f4(e,t){const n=Array.from(e.registrations.tools.values()),r=Array.from(e.registrations.prompts.values()),a=Array.from(e.registrations.resources.values()),o=Array.from(e.registrations.resourceTemplates.values()),i=a.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,uri:m.config.uri??null,mime_type:m.config.mimeType??null})),l=i.filter(m=>m.mime_type==="text/html+skybridge"),u=i.filter(m=>m.mime_type==="text/uri-list"||m.mime_type==="text/html"),f=i.filter(m=>m.mime_type==="text/html+mcp");return{transport:t,toolsNumber:e.registeredTools.length,resourcesNumber:e.registeredResources.length,promptsNumber:e.registeredPrompts.length,auth:!!e.oauthProvider,name:e.config.name,description:e.config.description??null,baseUrl:e.serverBaseUrl??null,toolNames:e.registeredTools.length>0?e.registeredTools:null,resourceNames:e.registeredResources.length>0?e.registeredResources:null,promptNames:e.registeredPrompts.length>0?e.registeredPrompts:null,tools:n.length>0?n.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,input_schema:m.config.schema?JSON.stringify(m.config.schema):null,output_schema:m.config.outputSchema?JSON.stringify(m.config.outputSchema):null})):null,resources:i.length>0?i:null,prompts:r.length>0?r.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,args:m.config.args?JSON.stringify(m.config.args):null})):null,templates:o.length>0?o.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null})):null,capabilities:{logging:!0,resources:{subscribe:!0,listChanged:!0}},appsSdkResources:l.length>0?l:null,appsSdkResourcesNumber:l.length,mcpUiResources:u.length>0?u:null,mcpUiResourcesNumber:u.length,mcpAppsResources:f.length>0?f:null,mcpAppsResourcesNumber:f.length}}ze(f4,"createServerRunEventData");var cd,cZ=(cd=class extends Yo{constructor(t){super(),this.data=t}get name(){return"server_run"}get properties(){return{transport:this.data.transport,tools_number:this.data.toolsNumber,resources_number:this.data.resourcesNumber,prompts_number:this.data.promptsNumber,auth:this.data.auth,name:this.data.name,description:this.data.description??null,base_url:this.data.baseUrl??null,tool_names:this.data.toolNames??null,resource_names:this.data.resourceNames??null,prompt_names:this.data.promptNames??null,tools:this.data.tools??null,resources:this.data.resources??null,prompts:this.data.prompts??null,templates:this.data.templates??null,capabilities:this.data.capabilities?JSON.stringify(this.data.capabilities):null,apps_sdk_resources:this.data.appsSdkResources?JSON.stringify(this.data.appsSdkResources):null,apps_sdk_resources_number:this.data.appsSdkResourcesNumber??0,mcp_ui_resources:this.data.mcpUiResources?JSON.stringify(this.data.mcpUiResources):null,mcp_ui_resources_number:this.data.mcpUiResourcesNumber??0,mcp_apps_resources:this.data.mcpAppsResources?JSON.stringify(this.data.mcpAppsResources):null,mcp_apps_resources_number:this.data.mcpAppsResourcesNumber??0}}},ze(cd,"ServerRunEvent"),cd),ud,uZ=(ud=class extends Yo{constructor(t){super(),this.data=t}get name(){return"server_initialize_call"}get properties(){return{protocol_version:this.data.protocolVersion,client_info:JSON.stringify(this.data.clientInfo),client_capabilities:JSON.stringify(this.data.clientCapabilities),session_id:this.data.sessionId??null}}},ze(ud,"ServerInitializeEvent"),ud),dd,dZ=(dd=class extends Yo{constructor(t){super(),this.data=t}get name(){return"server_tool_call"}get properties(){return{tool_name:this.data.toolName,length_input_argument:this.data.lengthInputArgument,success:this.data.success,error_type:this.data.errorType??null,execution_time_ms:this.data.executionTimeMs??null}}},ze(dd,"ServerToolCallEvent"),dd),fd,fZ=(fd=class extends Yo{constructor(t){super(),this.data=t}get name(){return"server_resource_call"}get properties(){return{name:this.data.name,description:this.data.description,contents:this.data.contents,success:this.data.success,error_type:this.data.errorType??null}}},ze(fd,"ServerResourceCallEvent"),fd),pd,pZ=(pd=class extends Yo{constructor(t){super(),this.data=t}get name(){return"server_prompt_call"}get properties(){return{name:this.data.name,description:this.data.description,success:this.data.success,error_type:this.data.errorType??null}}},ze(pd,"ServerPromptCallEvent"),pd),md,mZ=(md=class extends Yo{constructor(t){super(),this.data=t}get name(){return`server_context_${this.data.contextType}`}get properties(){return{context_type:this.data.contextType,notification_type:this.data.notificationType??null}}},ze(md,"ServerContextEvent"),md),hd,hZ=(hd=class extends Yo{constructor(t){super(),this.data=t}get name(){return"mcpclient_init"}get properties(){return{code_mode:this.data.codeMode,sandbox:this.data.sandbox,all_callbacks:this.data.allCallbacks,verify:this.data.verify,servers:this.data.servers,num_servers:this.data.numServers,is_browser:this.data.isBrowser}}},ze(hd,"MCPClientInitEvent"),hd),gd,gZ=(gd=class extends Yo{constructor(t){super(),this.data=t}get name(){return"connector_init"}get properties(){return{connector_type:this.data.connectorType,server_command:this.data.serverCommand??null,server_args:this.data.serverArgs??null,server_url:this.data.serverUrl??null,public_identifier:this.data.publicIdentifier??null}}},ze(gd,"ConnectorInitEvent"),gd),bd,bZ=(bd=class extends Yo{constructor(t){super(),this.data=t}get name(){return"client_add_server"}get properties(){const{serverName:t,serverConfig:n}=this.data,r=n.url;return{server_name:t,server_url_domain:r?this._extractHostname(r):null,transport:n.transport??null,has_auth:!!(n.authToken||n.authProvider)}}_extractHostname(t){try{return new URL(t).hostname}catch{return null}}},ze(bd,"ClientAddServerEvent"),bd),yd,yZ=(yd=class extends Yo{constructor(t){super(),this.data=t}get name(){return"client_remove_server"}get properties(){return{server_name:this.data.serverName}}},ze(yd,"ClientRemoveServerEvent"),yd);function p4(e){return e._llm_type||e.constructor.name.toLowerCase()}ze(p4,"getModelProvider");function m4(e){if("_identifyingParams"in e){const t=e._identifyingParams;if(typeof t=="object"&&t!==null){for(const n of["model","modelName","model_name","modelId","model_id","deploymentName","deployment_name"])if(n in t)return String(t[n])}}return e.model||e.modelName||e.constructor.name}ze(m4,"getModelName");function vZ(e){return[p4(e),m4(e)]}ze(vZ,"extractModelInfo");function Yb(){if(typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();if(typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.getRandomValues=="function"){const e=new Uint8Array(16);globalThis.crypto.getRandomValues(e);const t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.substring(0,8)}-${t.substring(8,12)}-${t.substring(12,16)}-${t.substring(16,20)}-${t.substring(20)}`}return`${Date.now()}-${Math.random().toString(36).substring(2,15)}-${Math.random().toString(36).substring(2,15)}`}ze(Yb,"generateUUID");function Zb(){if(typeof window<"u"&&window.crypto&&typeof window.crypto.getRandomValues=="function"){const e=new Uint8Array(8);return window.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}if(typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.getRandomValues=="function"){const e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}return Math.random().toString(36).substring(2,15)}ze(Zb,"secureRandomString");var Dj="mcp_use_user_id";function h4(){try{return typeof window<"u"&&typeof document<"u"?"browser":"unknown"}catch{return"unknown"}}ze(h4,"detectRuntimeEnvironment");function g4(e){if(e==="browser")try{if(typeof localStorage<"u")return localStorage.setItem("__mcp_use_test__","1"),localStorage.removeItem("__mcp_use_test__"),"localStorage"}catch{}return"session-only"}ze(g4,"getStorageCapability");var Xx=null;function b4(){return Xx===null&&(Xx=h4()),Xx}ze(b4,"getRuntimeEnvironment");var Fo,y4=(Fo=class{PROJECT_API_KEY="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";HOST="https://eu.i.posthog.com";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogBrowserClient=null;_posthogLoading=null;_runtimeEnvironment;_storageCapability;_source;constructor(){this._runtimeEnvironment=b4(),this._storageCapability=g4(this._runtimeEnvironment),this._source=this._getSourceFromLocalStorage()||this._runtimeEnvironment;const t=this._checkTelemetryDisabled(),n=this._runtimeEnvironment!=="unknown";t?(this._posthogBrowserClient=null,Fe.debug("Telemetry disabled via localStorage")):n?(Fe.info("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false in localStorage to disable."),this._posthogLoading=this._initPostHogBrowser()):(this._posthogBrowserClient=null,Fe.debug(`Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`))}_getSourceFromLocalStorage(){try{if(typeof localStorage<"u")return localStorage.getItem("MCP_USE_TELEMETRY_SOURCE")}catch{}return null}_checkTelemetryDisabled(){return typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}async _initPostHogBrowser(){try{const n=await Ua(()=>import("./module-D4IOASh4.js"),[]),r=n.default||n.posthog;if(!r||typeof r.init!="function")throw new Error("posthog-js module did not export expected interface");r.init(this.PROJECT_API_KEY,{api_host:this.HOST,persistence:"localStorage",autocapture:!1,capture_pageview:!1,disable_session_recording:!0,loaded:ze(()=>{Fe.debug("PostHog browser client initialized")},"loaded")}),this._posthogBrowserClient=r}catch(t){Fe.warn(`Failed to initialize PostHog browser telemetry: ${t}`),this._posthogBrowserClient=null}}get runtimeEnvironment(){return this._runtimeEnvironment}get storageCapability(){return this._storageCapability}static getInstance(){return Fo.instance||(Fo.instance=new Fo),Fo.instance}setSource(t){this._source=t;try{typeof localStorage<"u"&&localStorage.setItem("MCP_USE_TELEMETRY_SOURCE",t)}catch{}Fe.debug(`Telemetry source set to: ${t}`)}getSource(){return this._source}get isEnabled(){return this._posthogBrowserClient!==null}get userId(){if(this._currUserId)return this._currUserId;try{switch(this._storageCapability){case"localStorage":this._currUserId=this._getUserIdFromLocalStorage();break;case"session-only":default:try{this._currUserId=`session-${Yb()}`}catch{this._currUserId=`session-${Date.now()}-${Zb()}`}break}}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}_getUserIdFromLocalStorage(){try{if(typeof localStorage>"u")throw new Error("localStorage is not available");try{localStorage.setItem("__mcp_use_test__","1"),localStorage.removeItem("__mcp_use_test__")}catch(n){throw new Error(`localStorage is not writable: ${n}`)}let t=localStorage.getItem(Dj);if(!t){try{t=Yb()}catch{t=`${Date.now()}-${Zb()}`}localStorage.setItem(Dj,t)}return t}catch(t){Fe.debug(`Failed to access localStorage for user ID: ${t}`);let n;try{n=`session-${Yb()}`}catch{n=`session-${Date.now()}-${Zb()}`}return n}}async capture(t){if(this._posthogLoading&&await this._posthogLoading,!this._posthogBrowserClient)return;const n=this.userId,r={...t.properties};if(r.mcp_use_version=Sv(),r.language="typescript",r.source=this._source,r.runtime=this._runtimeEnvironment,this._posthogBrowserClient)try{this._posthogBrowserClient.capture(t.name,{...r,distinct_id:n})}catch(a){Fe.debug(`Failed to track PostHog Browser event ${t.name}: ${a}`)}}async trackAgentExecution(t){if(!this.isEnabled)return;const n=new lZ(t);await this.capture(n)}async trackServerRunFromServer(t,n){if(!this.isEnabled)return;const r=f4(t,n),a=new cZ(r);await this.capture(a)}async trackServerInitialize(t){if(!this.isEnabled)return;const n=new uZ(t);await this.capture(n)}async trackServerToolCall(t){if(!this.isEnabled)return;const n=new dZ(t);await this.capture(n)}async trackServerResourceCall(t){if(!this.isEnabled)return;const n=new fZ(t);await this.capture(n)}async trackServerPromptCall(t){if(!this.isEnabled)return;const n=new pZ(t);await this.capture(n)}async trackServerContext(t){if(!this.isEnabled)return;const n=new mZ(t);await this.capture(n)}async trackMCPClientInit(t){if(!this.isEnabled)return;const n=new hZ(t);await this.capture(n)}async trackConnectorInit(t){if(!this.isEnabled)return;const n=new gZ(t);await this.capture(n)}async trackClientAddServer(t,n){if(!this.isEnabled)return;const r=new bZ({serverName:t,serverConfig:n});await this.capture(r)}async trackClientRemoveServer(t){if(!this.isEnabled)return;const n=new yZ({serverName:t});await this.capture(n)}async trackUseMcpConnection(t){this.isEnabled&&await this.capture({name:"usemcp_connection",properties:{url_domain:new URL(t.url).hostname,transport_type:t.transportType,success:t.success,error_type:t.errorType??null,connection_time_ms:t.connectionTimeMs??null,has_oauth:t.hasOAuth,has_sampling:t.hasSampling,has_elicitation:t.hasElicitation}})}async trackUseMcpToolCall(t){this.isEnabled&&await this.capture({name:"usemcp_tool_call",properties:{tool_name:t.toolName,success:t.success,error_type:t.errorType??null,execution_time_ms:t.executionTimeMs??null}})}async trackUseMcpResourceRead(t){this.isEnabled&&await this.capture({name:"usemcp_resource_read",properties:{resource_uri_scheme:t.resourceUri.split(":")[0],success:t.success,error_type:t.errorType??null}})}identify(t,n){if(this._posthogBrowserClient)try{this._posthogBrowserClient.identify(t,n)}catch(r){Fe.debug(`Failed to identify user: ${r}`)}}reset(){if(this._posthogBrowserClient)try{this._posthogBrowserClient.reset()}catch(t){Fe.debug(`Failed to reset user: ${t}`)}this._currUserId=null}flush(){}shutdown(){}async trackPackageDownload(t){}},ze(Fo,"Telemetry"),Og(Fo,"instance",null),Fo),rs=y4;function wZ(e){rs.getInstance().setSource(e)}ze(wZ,"setTelemetrySource");const xZ=Object.freeze({status:"aborted"});function Oe(e,t,n){function r(l,u){if(l._zod||Object.defineProperty(l,"_zod",{value:{def:u,constr:i,traits:new Set},enumerable:!1}),l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,u);const f=i.prototype,m=Object.keys(f);for(let h=0;h<m.length;h++){const g=m[h];g in l||(l[g]=f[g].bind(l))}}const a=n?.Parent??Object;class o extends a{}Object.defineProperty(o,"name",{value:e});function i(l){var u;const f=n?.Parent?new o:this;r(f,l),(u=f._zod).deferred??(u.deferred=[]);for(const m of f._zod.deferred)m();return f}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Ku extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class v4 extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const NS={};function ol(e){return e&&Object.assign(NS,e),NS}function w4(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,a])=>t.indexOf(+r)===-1).map(([r,a])=>a)}function DTe(e,t="|"){return e.map(n=>NZ(n)).join(t)}function CS(e,t){return typeof t=="bigint"?t.toString():t}function _v(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function FT(e){return e==null}function BT(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function EZ(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let a=(r.split(".")[1]||"").length;if(a===0&&/\d?e-\d?/.test(r)){const u=r.match(/\d?e-(\d?)/);u?.[1]&&(a=Number.parseInt(u[1]))}const o=n>a?n:a,i=Number.parseInt(e.toFixed(o).replace(".","")),l=Number.parseInt(t.toFixed(o).replace(".",""));return i%l/10**o}const Lj=Symbol("evaluating");function Vn(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Lj)return r===void 0&&(r=Lj,r=n()),r},set(a){Object.defineProperty(e,t,{value:a})},configurable:!0})}function wc(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function xc(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function Mj(e){return JSON.stringify(e)}function SZ(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const x4="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Qp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const _Z=_v(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Ad(e){if(Qp(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Qp(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function E4(e){return Ad(e)?{...e}:Array.isArray(e)?[...e]:e}const TZ=new Set(["string","number","symbol"]);function Id(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pl(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function yt(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function NZ(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function CZ(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const RZ={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function kZ(e,t){const n=e._zod.def,r=xc(e._zod.def,{get shape(){const a={};for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(a[o]=n.shape[o])}return wc(this,"shape",a),a},checks:[]});return pl(e,r)}function AZ(e,t){const n=e._zod.def,r=xc(e._zod.def,{get shape(){const a={...e._zod.def.shape};for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete a[o]}return wc(this,"shape",a),a},checks:[]});return pl(e,r)}function IZ(e,t){if(!Ad(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const a=xc(e._zod.def,{get shape(){const o={...e._zod.def.shape,...t};return wc(this,"shape",o),o},checks:[]});return pl(e,a)}function OZ(e,t){if(!Ad(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return wc(this,"shape",r),r},checks:e._zod.def.checks};return pl(e,n)}function DZ(e,t){const n=xc(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return wc(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]});return pl(e,n)}function LZ(e,t,n){const r=xc(t._zod.def,{get shape(){const a=t._zod.def.shape,o={...a};if(n)for(const i in n){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(o[i]=e?new e({type:"optional",innerType:a[i]}):a[i])}else for(const i in a)o[i]=e?new e({type:"optional",innerType:a[i]}):a[i];return wc(this,"shape",o),o},checks:[]});return pl(t,r)}function MZ(e,t,n){const r=xc(t._zod.def,{get shape(){const a=t._zod.def.shape,o={...a};if(n)for(const i in n){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(o[i]=new e({type:"nonoptional",innerType:a[i]}))}else for(const i in a)o[i]=new e({type:"nonoptional",innerType:a[i]});return wc(this,"shape",o),o},checks:[]});return pl(t,r)}function Au(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Jl(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Dg(e){return typeof e=="string"?e:e?.message}function sl(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const a=Dg(e.inst?._zod.def?.error?.(e))??Dg(t?.error?.(e))??Dg(n.customError?.(e))??Dg(n.localeError?.(e))??"Invalid input";r.message=a}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function HT(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function em(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const S4=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,CS,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},_4=Oe("$ZodError",S4),Tv=Oe("$ZodError",S4,{Parent:Error});function jZ(e,t=n=>n.message){const n={},r=[];for(const a of e.issues)a.path.length>0?(n[a.path[0]]=n[a.path[0]]||[],n[a.path[0]].push(t(a))):r.push(t(a));return{formErrors:r,fieldErrors:n}}function PZ(e,t=n=>n.message){const n={_errors:[]},r=a=>{for(const o of a.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(i=>r({issues:i}));else if(o.code==="invalid_key")r({issues:o.issues});else if(o.code==="invalid_element")r({issues:o.issues});else if(o.path.length===0)n._errors.push(t(o));else{let i=n,l=0;for(;l<o.path.length;){const u=o.path[l];l===o.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(t(o))):i[u]=i[u]||{_errors:[]},i=i[u],l++}}};return r(e),n}function $Z(e){const t=[],n=e.map(r=>typeof r=="object"?r.key:r);for(const r of n)typeof r=="number"?t.push(`[${r}]`):typeof r=="symbol"?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function LTe(e){const t=[],n=[...e.issues].sort((r,a)=>(r.path??[]).length-(a.path??[]).length);for(const r of n)t.push(`✖ ${r.message}`),r.path?.length&&t.push(` → at ${$Z(r.path)}`);return t.join(`
3
3
  `)}const Nv=e=>(t,n,r,a)=>{const o=r?Object.assign(r,{async:!1}):{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Ku;if(i.issues.length){const l=new(a?.Err??e)(i.issues.map(u=>sl(u,o,ol())));throw x4(l,a?.callee),l}return i.value},MTe=Nv(Tv),Cv=e=>async(t,n,r,a)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){const l=new(a?.Err??e)(i.issues.map(u=>sl(u,o,ol())));throw x4(l,a?.callee),l}return i.value},jTe=Cv(Tv),Rv=e=>(t,n,r)=>{const a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Ku;return o.issues.length?{success:!1,error:new(e??_4)(o.issues.map(i=>sl(i,a,ol())))}:{success:!0,data:o.value}},T4=Rv(Tv),kv=e=>async(t,n,r)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},a);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(i=>sl(i,a,ol())))}:{success:!0,data:o.value}},UZ=kv(Tv),zZ=e=>(t,n,r)=>{const a=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Nv(e)(t,n,a)},FZ=e=>(t,n,r)=>Nv(e)(t,n,r),BZ=e=>async(t,n,r)=>{const a=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Cv(e)(t,n,a)},HZ=e=>async(t,n,r)=>Cv(e)(t,n,r),VZ=e=>(t,n,r)=>{const a=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Rv(e)(t,n,a)},GZ=e=>(t,n,r)=>Rv(e)(t,n,r),WZ=e=>async(t,n,r)=>{const a=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return kv(e)(t,n,a)},KZ=e=>async(t,n,r)=>kv(e)(t,n,r),YZ=/^[cC][^\s-]{8,}$/,ZZ=/^[0-9a-z]+$/,qZ=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,XZ=/^[0-9a-vA-V]{20}$/,JZ=/^[A-Za-z0-9]{27}$/,QZ=/^[a-zA-Z0-9_-]{21}$/,eq=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tq=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,jj=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,nq=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,rq="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function aq(){return new RegExp(rq,"u")}const oq=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,sq=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,iq=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,lq=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cq=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,N4=/^[A-Za-z0-9_-]*$/,uq=/^\+(?:[0-9]){6,14}[0-9]$/,C4="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",dq=new RegExp(`^${C4}$`);function R4(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function fq(e){return new RegExp(`^${R4(e)}$`)}function pq(e){const t=R4({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${C4}T(?:${r})$`)}const mq=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},hq=/^-?\d+$/,gq=/^-?\d+(?:\.\d+)?/,bq=/^(?:true|false)$/i,yq=/^null$/i,vq=/^[^A-Z]*$/,wq=/^[^a-z]*$/,Ba=Oe("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),k4={number:"number",bigint:"bigint",object:"date"},A4=Oe("$ZodCheckLessThan",(e,t)=>{Ba.init(e,t);const n=k4[typeof t.value];e._zod.onattach.push(r=>{const a=r._zod.bag,o=(t.inclusive?a.maximum:a.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?a.maximum=t.value:a.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),I4=Oe("$ZodCheckGreaterThan",(e,t)=>{Ba.init(e,t);const n=k4[typeof t.value];e._zod.onattach.push(r=>{const a=r._zod.bag,o=(t.inclusive?a.minimum:a.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?a.minimum=t.value:a.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),xq=Oe("$ZodCheckMultipleOf",(e,t)=>{Ba.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):EZ(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Eq=Oe("$ZodCheckNumberFormat",(e,t)=>{Ba.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[a,o]=RZ[t.format];e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,l.minimum=a,l.maximum=o,n&&(l.pattern=hq)}),e._zod.check=i=>{const l=i.value;if(n){if(!Number.isInteger(l)){i.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?i.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):i.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}l<a&&i.issues.push({origin:"number",input:l,code:"too_small",minimum:a,inclusive:!0,inst:e,continue:!t.abort}),l>o&&i.issues.push({origin:"number",input:l,code:"too_big",maximum:o,inst:e})}}),Sq=Oe("$ZodCheckMaxLength",(e,t)=>{var n;Ba.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!FT(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<a&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const a=r.value;if(a.length<=t.maximum)return;const i=HT(a);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),_q=Oe("$ZodCheckMinLength",(e,t)=>{var n;Ba.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!FT(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>a&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const a=r.value;if(a.length>=t.minimum)return;const i=HT(a);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),Tq=Oe("$ZodCheckLengthEquals",(e,t)=>{var n;Ba.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!FT(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag;a.minimum=t.length,a.maximum=t.length,a.length=t.length}),e._zod.check=r=>{const a=r.value,o=a.length;if(o===t.length)return;const i=HT(a),l=o>t.length;r.issues.push({origin:i,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Av=Oe("$ZodCheckStringFormat",(e,t)=>{var n,r;Ba.init(e,t),e._zod.onattach.push(a=>{const o=a._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=a=>{t.pattern.lastIndex=0,!t.pattern.test(a.value)&&a.issues.push({origin:"string",code:"invalid_format",format:t.format,input:a.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Nq=Oe("$ZodCheckRegex",(e,t)=>{Av.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Cq=Oe("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vq),Av.init(e,t)}),Rq=Oe("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=wq),Av.init(e,t)}),kq=Oe("$ZodCheckIncludes",(e,t)=>{Ba.init(e,t);const n=Id(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(a=>{const o=a._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=a=>{a.value.includes(t.includes,t.position)||a.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:a.value,inst:e,continue:!t.abort})}}),Aq=Oe("$ZodCheckStartsWith",(e,t)=>{Ba.init(e,t);const n=new RegExp(`^${Id(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Iq=Oe("$ZodCheckEndsWith",(e,t)=>{Ba.init(e,t);const n=new RegExp(`.*${Id(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),Oq=Oe("$ZodCheckOverwrite",(e,t)=>{Ba.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class Dq{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
4
4
  `).filter(i=>i),a=Math.min(...r.map(i=>i.length-i.trimStart().length)),o=r.map(i=>i.slice(a)).map(i=>" ".repeat(this.indent*2)+i);for(const i of o)this.content.push(i)}compile(){const t=Function,n=this?.args,a=[...(this?.content??[""]).map(o=>` ${o}`)];return new t(...n,a.join(`
5
5
  `))}}const Lq={major:4,minor:2,patch:0},Gn=Oe("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Lq;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const a of r)for(const o of a._zod.onattach)o(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const a=(i,l,u)=>{let f=Au(i),m;for(const h of l){if(h._zod.def.when){if(!h._zod.def.when(i))continue}else if(f)continue;const g=i.issues.length,b=h._zod.check(i);if(b instanceof Promise&&u?.async===!1)throw new Ku;if(m||b instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await b,i.issues.length!==g&&(f||(f=Au(i,g)))});else{if(i.issues.length===g)continue;f||(f=Au(i,g))}}return m?m.then(()=>i):i},o=(i,l,u)=>{if(Au(i))return i.aborted=!0,i;const f=a(l,r,u);if(f instanceof Promise){if(u.async===!1)throw new Ku;return f.then(m=>e._zod.parse(m,u))}return e._zod.parse(f,u)};e._zod.run=(i,l)=>{if(l.skipChecks)return e._zod.parse(i,l);if(l.direction==="backward"){const f=e._zod.parse({value:i.value,issues:[]},{...l,skipChecks:!0});return f instanceof Promise?f.then(m=>o(m,i,l)):o(f,i,l)}const u=e._zod.parse(i,l);if(u instanceof Promise){if(l.async===!1)throw new Ku;return u.then(f=>a(f,r,l))}return a(u,r,l)}}e["~standard"]={validate:a=>{try{const o=T4(e,a);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return UZ(e,a).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),VT=Oe("$ZodString",(e,t)=>{Gn.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??mq(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),lr=Oe("$ZodStringFormat",(e,t)=>{Av.init(e,t),VT.init(e,t)}),Mq=Oe("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=tq),lr.init(e,t)}),jq=Oe("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=jj(r))}else t.pattern??(t.pattern=jj());lr.init(e,t)}),Pq=Oe("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=nq),lr.init(e,t)}),$q=Oe("$ZodURL",(e,t)=>{lr.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),a=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(a.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(a.protocol.endsWith(":")?a.protocol.slice(0,-1):a.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=a.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Uq=Oe("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=aq()),lr.init(e,t)}),zq=Oe("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=QZ),lr.init(e,t)}),Fq=Oe("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=YZ),lr.init(e,t)}),Bq=Oe("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ZZ),lr.init(e,t)}),Hq=Oe("$ZodULID",(e,t)=>{t.pattern??(t.pattern=qZ),lr.init(e,t)}),Vq=Oe("$ZodXID",(e,t)=>{t.pattern??(t.pattern=XZ),lr.init(e,t)}),Gq=Oe("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=JZ),lr.init(e,t)}),Wq=Oe("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=pq(t)),lr.init(e,t)}),Kq=Oe("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=dq),lr.init(e,t)}),Yq=Oe("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=fq(t)),lr.init(e,t)}),Zq=Oe("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=eq),lr.init(e,t)}),qq=Oe("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=oq),lr.init(e,t),e._zod.bag.format="ipv4"}),Xq=Oe("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=sq),lr.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Jq=Oe("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=iq),lr.init(e,t)}),Qq=Oe("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=lq),lr.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[a,o]=r;if(!o)throw new Error;const i=Number(o);if(`${i}`!==o)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${a}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function O4(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const eX=Oe("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=cq),lr.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{O4(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function tX(e){if(!N4.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return O4(n)}const nX=Oe("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=N4),lr.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{tX(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),rX=Oe("$ZodE164",(e,t)=>{t.pattern??(t.pattern=uq),lr.init(e,t)});function aX(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const a=JSON.parse(atob(r));return!("typ"in a&&a?.typ!=="JWT"||!a.alg||t&&(!("alg"in a)||a.alg!==t))}catch{return!1}}const oX=Oe("$ZodJWT",(e,t)=>{lr.init(e,t),e._zod.check=n=>{aX(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),D4=Oe("$ZodNumber",(e,t)=>{Gn.init(e,t),e._zod.pattern=e._zod.bag.pattern??gq,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const a=n.value;if(typeof a=="number"&&!Number.isNaN(a)&&Number.isFinite(a))return n;const o=typeof a=="number"?Number.isNaN(a)?"NaN":Number.isFinite(a)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:a,inst:e,...o?{received:o}:{}}),n}}),sX=Oe("$ZodNumberFormat",(e,t)=>{Eq.init(e,t),D4.init(e,t)}),iX=Oe("$ZodBoolean",(e,t)=>{Gn.init(e,t),e._zod.pattern=bq,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const a=n.value;return typeof a=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:a,inst:e}),n}}),lX=Oe("$ZodNull",(e,t)=>{Gn.init(e,t),e._zod.pattern=yq,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const a=n.value;return a===null||n.issues.push({expected:"null",code:"invalid_type",input:a,inst:e}),n}}),cX=Oe("$ZodAny",(e,t)=>{Gn.init(e,t),e._zod.parse=n=>n}),uX=Oe("$ZodUnknown",(e,t)=>{Gn.init(e,t),e._zod.parse=n=>n}),dX=Oe("$ZodNever",(e,t)=>{Gn.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Pj(e,t,n){e.issues.length&&t.issues.push(...Jl(n,e.issues)),t.value[n]=e.value}const fX=Oe("$ZodArray",(e,t)=>{Gn.init(e,t),e._zod.parse=(n,r)=>{const a=n.value;if(!Array.isArray(a))return n.issues.push({expected:"array",code:"invalid_type",input:a,inst:e}),n;n.value=Array(a.length);const o=[];for(let i=0;i<a.length;i++){const l=a[i],u=t.element._zod.run({value:l,issues:[]},r);u instanceof Promise?o.push(u.then(f=>Pj(f,n,i))):Pj(u,n,i)}return o.length?Promise.all(o).then(()=>n):n}});function Sy(e,t,n,r){e.issues.length&&t.issues.push(...Jl(n,e.issues)),e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function L4(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=CZ(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function M4(e,t,n,r,a,o){const i=[],l=a.keySet,u=a.catchall._zod,f=u.def.type;for(const m in t){if(l.has(m))continue;if(f==="never"){i.push(m);continue}const h=u.run({value:t[m],issues:[]},r);h instanceof Promise?e.push(h.then(g=>Sy(g,n,m,t))):Sy(h,n,m,t)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}const pX=Oe("$ZodObject",(e,t)=>{if(Gn.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const l=t.shape;Object.defineProperty(t,"shape",{get:()=>{const u={...l};return Object.defineProperty(t,"shape",{value:u}),u}})}const r=_v(()=>L4(t));Vn(e._zod,"propValues",()=>{const l=t.shape,u={};for(const f in l){const m=l[f]._zod;if(m.values){u[f]??(u[f]=new Set);for(const h of m.values)u[f].add(h)}}return u});const a=Qp,o=t.catchall;let i;e._zod.parse=(l,u)=>{i??(i=r.value);const f=l.value;if(!a(f))return l.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),l;l.value={};const m=[],h=i.shape;for(const g of i.keys){const E=h[g]._zod.run({value:f[g],issues:[]},u);E instanceof Promise?m.push(E.then(x=>Sy(x,l,g,f))):Sy(E,l,g,f)}return o?M4(m,f,l,u,r.value,e):m.length?Promise.all(m).then(()=>l):l}}),mX=Oe("$ZodObjectJIT",(e,t)=>{pX.init(e,t);const n=e._zod.parse,r=_v(()=>L4(t)),a=g=>{const b=new Dq(["shape","payload","ctx"]),E=r.value,x=T=>{const k=Mj(T);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};b.write("const input = payload.value;");const w=Object.create(null);let S=0;for(const T of E.keys)w[T]=`key_${S++}`;b.write("const newResult = {};");for(const T of E.keys){const k=w[T],R=Mj(T);b.write(`const ${k} = ${x(T)};`),b.write(`
@@ -32,7 +32,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
32
32
  `;break;case"id":l=w.includes("\0")?void 0:w;break;case"retry":/^\d+$/.test(w)?r(parseInt(w,10)):n(new E$(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:S}));break;default:n(new E$(`Unknown field "${x.length>20?`${x.slice(0,20)}…`:x}"`,{type:"unknown-field",field:x,value:w,line:S}));break}}function b(){u.length>0&&t({id:l,event:f||void 0,data:u.endsWith(`
33
33
  `)?u.slice(0,-1):u}),l=void 0,u="",f=""}function E(x={}){o&&x.consume&&h(o),i=!0,l=void 0,u="",f="",o=""}return{feed:m,reset:E}}function Are(e){const t=[];let n="",r=0;for(;r<e.length;){const a=e.indexOf("\r",r),o=e.indexOf(`
34
34
  `,r);let i=-1;if(a!==-1&&o!==-1?i=Math.min(a,o):a!==-1?a===e.length-1?i=-1:i=a:o!==-1&&(i=o),i===-1){n=e.slice(r);break}else{const l=e.slice(r,i);t.push(l),r=i+1,e[r-1]==="\r"&&e[r]===`
35
- `&&r++}}return[t,n]}class Ire extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let a;super({start(o){a=bB({onEvent:i=>{o.enqueue(i)},onError(i){t==="terminate"?o.error(i):typeof t=="function"&&t(i)},onRetry:n,onComment:r})},transform(o){a.feed(o)}})}}const Ore={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Vi extends Error{constructor(t,n){super(`Streamable HTTP error: ${n}`),this.code=t}}class Dre{constructor(t,n){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=n?.requestInit,this._authProvider=n?.authProvider,this._fetch=n?.fetch,this._fetchWithInit=rB(n?.fetch,n?.requestInit),this._sessionId=n?.sessionId,this._reconnectionOptions=n?.reconnectionOptions??Ore}async _authThenStart(){if(!this._authProvider)throw new yo("No auth provider");let t;try{t=await Ks(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw this.onerror?.(n),n}if(t!=="AUTHORIZED")throw new yo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const t={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(t.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const n=Dy(this._requestInit?.headers);return new Headers({...t,...n})}async _startOrAuthSse(t){const{resumptionToken:n}=t;try{const r=await this._commonHeaders();r.set("Accept","text/event-stream"),n&&r.set("last-event-id",n);const a=await(this._fetch??fetch)(this._url,{method:"GET",headers:r,signal:this._abortController?.signal});if(!a.ok){if(await a.body?.cancel(),a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new Vi(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,t,!0)}catch(r){throw this.onerror?.(r),r}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const n=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,a=this._reconnectionOptions.maxReconnectionDelay;return Math.min(n*Math.pow(r,t),a)}_scheduleReconnection(t,n=0){const r=this._reconnectionOptions.maxRetries;if(n>=r){this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`));return}const a=this._getNextReconnectionDelay(n);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(t,n+1)})},a)}_handleSseStream(t,n,r){if(!t)return;const{onresumptiontoken:a,replayMessageId:o}=n;let i,l=!1,u=!1;(async()=>{try{const m=t.pipeThrough(new TextDecoderStream).pipeThrough(new Ire({onRetry:b=>{this._serverRetryMs=b}})).getReader();for(;;){const{value:b,done:E}=await m.read();if(E)break;if(b.id&&(i=b.id,l=!0,a?.(b.id)),!!b.data&&(!b.event||b.event==="message"))try{const x=qb.parse(JSON.parse(b.data));Sp(x)&&(u=!0,o!==void 0&&(x.id=o)),this.onmessage?.(x)}catch(x){this.onerror?.(x)}}(r||l)&&!u&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:o},0)}catch(m){if(this.onerror?.(new Error(`SSE stream disconnected: ${m}`)),(r||l)&&!u&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:o},0)}catch(b){this.onerror?.(new Error(`Failed to reconnect: ${b instanceof Error?b.message:String(b)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new yo("No auth provider");if(await Ks(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new yo("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,n){try{const{resumptionToken:r,onresumptiontoken:a}=n||{};if(r){this._startOrAuthSse({resumptionToken:r,replayMessageId:IS(t)?t.id:void 0}).catch(g=>this.onerror?.(g));return}const o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");const i={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(t),signal:this._abortController?.signal},l=await(this._fetch??fetch)(this._url,i),u=l.headers.get("mcp-session-id");if(u&&(this._sessionId=u),!l.ok){const g=await l.text().catch(()=>null);if(l.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Vi(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:b,scope:E}=nm(l);if(this._resourceMetadataUrl=b,this._scope=E,await Ks(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new yo;return this._hasCompletedAuthFlow=!0,this.send(t)}if(l.status===403&&this._authProvider){const{resourceMetadataUrl:b,scope:E,error:x}=nm(l);if(x==="insufficient_scope"){const w=l.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===w)throw new Vi(403,"Server returned 403 after trying upscoping");if(E&&(this._scope=E),b&&(this._resourceMetadataUrl=b),this._lastUpscopingHeader=w??void 0,await Ks(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new yo;return this.send(t)}}throw new Vi(l.status,`Error POSTing to endpoint: ${g}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,l.status===202){await l.body?.cancel(),xee(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(g=>this.onerror?.(g));return}const m=(Array.isArray(t)?t:[t]).filter(g=>"method"in g&&"id"in g&&g.id!==void 0).length>0,h=l.headers.get("content-type");if(m)if(h?.includes("text/event-stream"))this._handleSseStream(l.body,{onresumptiontoken:a},!1);else if(h?.includes("application/json")){const g=await l.json(),b=Array.isArray(g)?g.map(E=>qb.parse(E)):[qb.parse(g)];for(const E of b)this.onmessage?.(E)}else throw await l.body?.cancel(),new Vi(-1,`Unexpected content type: ${h}`);else await l.body?.cancel()}catch(r){throw this.onerror?.(r),r}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const t=await this._commonHeaders(),n={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._url,n);if(await r.body?.cancel(),!r.ok&&r.status!==405)throw new Vi(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,n){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:n?.onresumptiontoken})}}class S$ extends Event{constructor(t,n){var r,a;super(t),this.code=(r=n?.code)!=null?r:void 0,this.message=(a=n?.message)!=null?a:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,r){return r(_$(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(_$(this),n)}}function Lre(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function VS(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(VS).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${VS(e.cause)}`:e.message:`${e}`}function _$(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var yB=e=>{throw TypeError(e)},wN=(e,t,n)=>t.has(e)||yB("Cannot "+n),un=(e,t,n)=>(wN(e,t,"read from private field"),n?n.call(e):t.get(e)),Lr=(e,t,n)=>t.has(e)?yB("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),or=(e,t,n,r)=>(wN(e,t,"write to private field"),t.set(e,n),n),Vs=(e,t,n)=>(wN(e,t,"access private method"),n),$a,Zl,wu,Jb,$y,jp,Ou,Pp,Wi,xu,Yu,Eu,_p,jo,GS,WS,KS,T$,YS,ZS,Tp,qS,XS;class Qb extends EventTarget{constructor(t,n){var r,a;super(),Lr(this,jo),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Lr(this,$a),Lr(this,Zl),Lr(this,wu),Lr(this,Jb),Lr(this,$y),Lr(this,jp),Lr(this,Ou),Lr(this,Pp,null),Lr(this,Wi),Lr(this,xu),Lr(this,Yu,null),Lr(this,Eu,null),Lr(this,_p,null),Lr(this,WS,async o=>{var i;un(this,xu).reset();const{body:l,redirected:u,status:f,headers:m}=o;if(f===204){Vs(this,jo,Tp).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?or(this,wu,new URL(o.url)):or(this,wu,void 0),f!==200){Vs(this,jo,Tp).call(this,`Non-200 status code (${f})`,f);return}if(!(m.get("content-type")||"").startsWith("text/event-stream")){Vs(this,jo,Tp).call(this,'Invalid content type, expected "text/event-stream"',f);return}if(un(this,$a)===this.CLOSED)return;or(this,$a,this.OPEN);const h=new Event("open");if((i=un(this,_p))==null||i.call(this,h),this.dispatchEvent(h),typeof l!="object"||!l||!("getReader"in l)){Vs(this,jo,Tp).call(this,"Invalid response body, expected a web ReadableStream",f),this.close();return}const g=new TextDecoder,b=l.getReader();let E=!0;do{const{done:x,value:w}=await b.read();w&&un(this,xu).feed(g.decode(w,{stream:!x})),x&&(E=!1,un(this,xu).reset(),Vs(this,jo,qS).call(this))}while(E)}),Lr(this,KS,o=>{or(this,Wi,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Vs(this,jo,qS).call(this,VS(o))}),Lr(this,YS,o=>{typeof o.id=="string"&&or(this,Pp,o.id);const i=new MessageEvent(o.event||"message",{data:o.data,origin:un(this,wu)?un(this,wu).origin:un(this,Zl).origin,lastEventId:o.id||""});un(this,Eu)&&(!o.event||o.event==="message")&&un(this,Eu).call(this,i),this.dispatchEvent(i)}),Lr(this,ZS,o=>{or(this,jp,o)}),Lr(this,XS,()=>{or(this,Ou,void 0),un(this,$a)===this.CONNECTING&&Vs(this,jo,GS).call(this)});try{if(t instanceof URL)or(this,Zl,t);else if(typeof t=="string")or(this,Zl,new URL(t,Mre()));else throw new Error("Invalid URL")}catch{throw Lre("An invalid or illegal string was specified")}or(this,xu,bB({onEvent:un(this,YS),onRetry:un(this,ZS)})),or(this,$a,this.CONNECTING),or(this,jp,3e3),or(this,$y,(r=n?.fetch)!=null?r:globalThis.fetch),or(this,Jb,(a=n?.withCredentials)!=null?a:!1),Vs(this,jo,GS).call(this)}get readyState(){return un(this,$a)}get url(){return un(this,Zl).href}get withCredentials(){return un(this,Jb)}get onerror(){return un(this,Yu)}set onerror(t){or(this,Yu,t)}get onmessage(){return un(this,Eu)}set onmessage(t){or(this,Eu,t)}get onopen(){return un(this,_p)}set onopen(t){or(this,_p,t)}addEventListener(t,n,r){const a=n;super.addEventListener(t,a,r)}removeEventListener(t,n,r){const a=n;super.removeEventListener(t,a,r)}close(){un(this,Ou)&&clearTimeout(un(this,Ou)),un(this,$a)!==this.CLOSED&&(un(this,Wi)&&un(this,Wi).abort(),or(this,$a,this.CLOSED),or(this,Wi,void 0))}}$a=new WeakMap,Zl=new WeakMap,wu=new WeakMap,Jb=new WeakMap,$y=new WeakMap,jp=new WeakMap,Ou=new WeakMap,Pp=new WeakMap,Wi=new WeakMap,xu=new WeakMap,Yu=new WeakMap,Eu=new WeakMap,_p=new WeakMap,jo=new WeakSet,GS=function(){or(this,$a,this.CONNECTING),or(this,Wi,new AbortController),un(this,$y)(un(this,Zl),Vs(this,jo,T$).call(this)).then(un(this,WS)).catch(un(this,KS))},WS=new WeakMap,KS=new WeakMap,T$=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...un(this,Pp)?{"Last-Event-ID":un(this,Pp)}:void 0},cache:"no-store",signal:(e=un(this,Wi))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},YS=new WeakMap,ZS=new WeakMap,Tp=function(e,t){var n;un(this,$a)!==this.CLOSED&&or(this,$a,this.CLOSED);const r=new S$("error",{code:t,message:e});(n=un(this,Yu))==null||n.call(this,r),this.dispatchEvent(r)},qS=function(e,t){var n;if(un(this,$a)===this.CLOSED)return;or(this,$a,this.CONNECTING);const r=new S$("error",{code:t,message:e});(n=un(this,Yu))==null||n.call(this,r),this.dispatchEvent(r),or(this,Ou,setTimeout(un(this,XS),un(this,jp)))},XS=new WeakMap,Qb.CONNECTING=0,Qb.OPEN=1,Qb.CLOSED=2;function Mre(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}class jre extends Error{constructor(t,n,r){super(`SSE error: ${n}`),this.code=t,this.event=r}}class Pre{constructor(t,n){this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=n?.eventSourceInit,this._requestInit=n?.requestInit,this._authProvider=n?.authProvider,this._fetch=n?.fetch,this._fetchWithInit=rB(n?.fetch,n?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new yo("No auth provider");let t;try{t=await Ks(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw this.onerror?.(n),n}if(t!=="AUTHORIZED")throw new yo;return await this._startOrAuth()}async _commonHeaders(){const t={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(t.Authorization=`Bearer ${r.access_token}`)}this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const n=Dy(this._requestInit?.headers);return new Headers({...t,...n})}_startOrAuth(){const t=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((n,r)=>{this._eventSource=new Qb(this._url.href,{...this._eventSourceInit,fetch:async(a,o)=>{const i=await this._commonHeaders();i.set("Accept","text/event-stream");const l=await t(a,{...o,headers:i});if(l.status===401&&l.headers.has("www-authenticate")){const{resourceMetadataUrl:u,scope:f}=nm(l);this._resourceMetadataUrl=u,this._scope=f}return l}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{if(a.code===401&&this._authProvider){this._authThenStart().then(n,r);return}const o=new jre(a.code,a.message,a);r(o),this.onerror?.(o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{const o=a;try{if(this._endpoint=new URL(o.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(i){r(i),this.onerror?.(i),this.close();return}n()}),this._eventSource.onmessage=a=>{const o=a;let i;try{i=qb.parse(JSON.parse(o.data))}catch(l){this.onerror?.(l);return}this.onmessage?.(i)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(t){if(!this._authProvider)throw new yo("No auth provider");if(await Ks(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new yo("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(t){if(!this._endpoint)throw new Error("Not connected");try{const n=await this._commonHeaders();n.set("content-type","application/json");const r={...this._requestInit,method:"POST",headers:n,body:JSON.stringify(t),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._endpoint,r);if(!a.ok){const o=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){const{resourceMetadataUrl:i,scope:l}=nm(a);if(this._resourceMetadataUrl=i,this._scope=l,await Ks(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new yo;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${a.status}): ${o}`)}await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}setProtocolVersion(t){this._protocolVersion=t}}var wd,$re=(wd=class{connector;autoConnect;constructor(t,n=!0){this.connector=t,this.autoConnect=n}async connect(){await this.connector.connect()}async disconnect(){await this.connector.disconnect()}async initialize(){!this.isConnected&&this.autoConnect&&await this.connect(),await this.connector.initialize()}get isConnected(){return this.connector&&this.connector.isClientConnected}on(t,n){t==="notification"&&this.connector.onNotification(n)}async setRoots(t){return this.connector.setRoots(t)}getRoots(){return this.connector.getRoots()}get tools(){return this.connector.tools}async listTools(t){return this.connector.listTools(t)}get serverCapabilities(){return this.connector.serverCapabilities}get serverInfo(){return this.connector.serverInfo}async callTool(t,n={},r){return this.connector.callTool(t,n,r)}async listResources(t,n){return this.connector.listResources(t,n)}async listAllResources(t){return this.connector.listAllResources(t)}async listResourceTemplates(t){return this.connector.listResourceTemplates(t)}async readResource(t,n){return this.connector.readResource(t,n)}async subscribeToResource(t,n){return this.connector.subscribeToResource(t,n)}async unsubscribeFromResource(t,n){return this.connector.unsubscribeFromResource(t,n)}async listPrompts(){return this.connector.listPrompts()}async getPrompt(t,n){return this.connector.getPrompt(t,n)}async request(t,n=null,r){return this.connector.request(t,n,r)}},ze(wd,"MCPSession"),wd),xd,Ure=(xd=class{config={};sessions={};activeSessions=[];constructor(t){t&&(this.config=t)}static fromDict(t){throw new Error("fromDict must be implemented by concrete class")}addServer(t,n){this.config.mcpServers=this.config.mcpServers||{},this.config.mcpServers[t]=n,rs.getInstance().trackClientAddServer(t,n)}removeServer(t){this.config.mcpServers?.[t]&&(delete this.config.mcpServers[t],this.activeSessions=this.activeSessions.filter(n=>n!==t),rs.getInstance().trackClientRemoveServer(t))}getServerNames(){return Object.keys(this.config.mcpServers??{})}getServerConfig(t){return this.config.mcpServers?.[t]}getConfig(){return this.config??{}}async createSession(t,n=!0){const r=this.config.mcpServers??{};if(Object.keys(r).length===0&&Fe.warn("No MCP servers defined in config"),!r[t])throw new Error(`Server '${t}' not found in config`);const a=this.createConnectorFromConfig(r[t]),o=new $re(a);return n&&await o.initialize(),this.sessions[t]=o,this.activeSessions.includes(t)||this.activeSessions.push(t),o}async createAllSessions(t=!0){const n=this.config.mcpServers??{};Object.keys(n).length===0&&Fe.warn("No MCP servers defined in config");for(const r of Object.keys(n))await this.createSession(r,t);return this.sessions}getSession(t){const n=this.sessions[t];return n||null}requireSession(t){const n=this.sessions[t];if(!n)throw new Error(`Session '${t}' not found. Available sessions: ${this.activeSessions.join(", ")||"none"}`);return n}getAllActiveSessions(){return Object.fromEntries(this.activeSessions.map(t=>[t,this.sessions[t]]))}async closeSession(t){const n=this.sessions[t];if(!n){Fe.warn(`No session exists for server ${t}, nothing to close`);return}try{Fe.debug(`Closing session for server ${t}`),await n.disconnect()}catch(r){Fe.error(`Error closing session for server '${t}': ${r}`)}finally{delete this.sessions[t],this.activeSessions=this.activeSessions.filter(r=>r!==t)}}async closeAllSessions(){const t=Object.keys(this.sessions),n=[];for(const r of t)try{Fe.debug(`Closing session for server ${r}`),await this.closeSession(r)}catch(a){const o=`Failed to close session for server '${r}': ${a}`;Fe.error(o),n.push(o)}n.length?Fe.error(`Encountered ${n.length} errors while closing sessions`):Fe.debug("All sessions closed successfully")}},ze(xd,"BaseMCPClient"),xd),Ed,zre=(Ed=class{_readyPromise;_readyResolver;_donePromise;_doneResolver;_exception=null;_connection=null;_task=null;_abortController=null;constructor(){this.reset()}async start(){if(this.reset(),Fe.debug(`Starting ${this.constructor.name}`),this._task=this.connectionTask(),await this._readyPromise,this._exception)throw this._exception;if(this._connection===null)throw new Error("Connection was not established");return this._connection}async stop(){if(this._task&&this._abortController){Fe.debug(`Cancelling ${this.constructor.name} task`),this._abortController.abort();try{await this._task}catch(t){t instanceof Error&&t.name==="AbortError"?Fe.debug(`${this.constructor.name} task aborted successfully`):Fe.warn(`Error stopping ${this.constructor.name} task: ${t}`)}}await this._donePromise,Fe.debug(`${this.constructor.name} task completed`)}reset(){this._readyPromise=new Promise(t=>this._readyResolver=t),this._donePromise=new Promise(t=>this._doneResolver=t),this._exception=null,this._connection=null,this._task=null,this._abortController=new AbortController}async connectionTask(){Fe.debug(`Running ${this.constructor.name} task`);try{this._connection=await this.establishConnection(),Fe.debug(`${this.constructor.name} connected successfully`),this._readyResolver(),await this.waitForAbort()}catch(t){this._exception=t,Fe.error(`Error in ${this.constructor.name} task: ${t}`),this._readyResolver()}finally{if(this._connection!==null){try{await this.closeConnection(this._connection)}catch(t){Fe.warn(`Error closing connection in ${this.constructor.name}: ${t}`)}this._connection=null}this._doneResolver()}}async waitForAbort(){return new Promise((t,n)=>{if(!this._abortController)return;const r=this._abortController.signal;if(r.aborted){t();return}const a=ze(()=>{r.removeEventListener("abort",a),t()},"onAbort");r.addEventListener("abort",a)})}},ze(Ed,"ConnectionManager"),Ed),Sd,Fre=(Sd=class extends zre{url;opts;_transport=null;reinitializing=!1;constructor(t,n){super(),this.url=typeof t=="string"?new URL(t):t,this.opts=n}async establishConnection(){const t=new Pre(this.url,this.opts),n=t.send.bind(t);return t.send=async r=>{const a=ze(async o=>{if(Array.isArray(o))for(const i of o)await n(i);else await n(o)},"sendMessage");try{await a(r)}catch(o){if(o?.code===404&&t.sessionId&&!this.reinitializing){Fe.warn("[SSE] Session not found (404), re-initializing per MCP spec..."),this.reinitializing=!0;try{t.sessionId=void 0,await this.reinitialize(t),Fe.info("[SSE] Re-initialization successful, retrying request"),await a(r)}finally{this.reinitializing=!1}}else throw o}},this._transport=t,Fe.debug(`${this.constructor.name} connected successfully`),t}async reinitialize(t){Fe.debug("[SSE] Re-initialization triggered")}async closeConnection(t){if(this._transport)try{await this._transport.close()}catch(n){Fe.warn(`Error closing SSE transport: ${n}`)}finally{this._transport=null}}},ze(Sd,"SseConnectionManager"),Sd),_d,Bre=(_d=class extends Pte{baseUrl;headers;timeout;sseReadTimeout;clientInfo;preferSse;disableSseFallback;gatewayUrl;serverId;transportType=null;streamableTransport=null;constructor(t,n={}){super(n);const r=t.replace(/\/$/,"");this.gatewayUrl=n.gatewayUrl,this.serverId=n.serverId,this.gatewayUrl?(this.baseUrl=this.gatewayUrl.replace(/\/$/,""),this.headers={...n.headers??{}},this.headers["X-Target-URL"]=r,this.serverId&&(this.headers["X-Server-Id"]=this.serverId)):(this.baseUrl=r,this.headers={...n.headers??{}}),n.authToken&&(this.headers.Authorization=`Bearer ${n.authToken}`),this.timeout=n.timeout??1e4,this.sseReadTimeout=n.sseReadTimeout??3e5,this.clientInfo=n.clientInfo??{name:"http-connector",version:"1.0.0"},this.preferSse=n.preferSse??!1,this.disableSseFallback=n.disableSseFallback??!1}async connect(){if(this.connected){Fe.debug("Already connected to MCP implementation");return}const t=this.baseUrl;if(this.preferSse){Fe.debug(`Connecting to MCP implementation via HTTP/SSE: ${t}`),await this.connectWithSse(t);return}Fe.debug(`Connecting to MCP implementation via HTTP: ${t}`);try{Fe.info("🔄 Attempting streamable HTTP transport..."),await this.connectWithStreamableHttp(t),Fe.info("✅ Successfully connected via streamable HTTP")}catch(n){console.log("error in http connector connect",n);let r="Unknown error",a=!1,o,i=null;if(n instanceof Vi?i=n:n instanceof Error&&n.cause instanceof Vi&&(i=n.cause),i)a=i.code===401,o=i.code,console.log("Captured HTTP status code:",o),i.code===400&&i.message.includes("Missing session ID")?(r="Server requires session ID (FastMCP compatibility) - using SSE transport",Fe.warn(`⚠️ ${r}`)):i.code===404||i.code===405?(r=`Server returned ${i.code} - server likely doesn't support streamable HTTP`,Fe.debug(r)):(r=`Server returned ${i.code}: ${i.message}`,Fe.debug(r));else if(n instanceof Error){const l=n.toString(),u=n.message||"";a=l.includes("401")||u.includes("Unauthorized"),l.includes("Missing session ID")||l.includes("Bad Request: Missing session ID")||u.includes("FastMCP session ID error")?(r="Server requires session ID (FastMCP compatibility) - using SSE transport",Fe.warn(`⚠️ ${r}`)):l.includes("405 Method Not Allowed")||l.includes("404 Not Found")?(r="Server doesn't support streamable HTTP (405/404)",Fe.debug(r)):(r=`Streamable HTTP failed: ${n.message}`,Fe.debug(r))}if(a){Fe.info("Authentication required - skipping SSE fallback"),await this.cleanupResources();const l=new Error("Authentication required");throw l.code=401,l}Fe.info("🔄 Falling back to SSE transport...");try{await this.connectWithSse(t)}catch(l){if(console.error("Failed to connect with both transports:"),console.error(` Streamable HTTP: ${r}`),console.error(` SSE: ${l}`),await this.cleanupResources(),l?.message?.includes("401")||l?.message?.includes("Unauthorized")){const m=new Error("Authentication required");throw m.code=401,m}const f=new Error(`Could not connect to server with any available transport. Streamable HTTP: ${r}`);throw o!==void 0&&(Object.defineProperty(f,"code",{value:o,writable:!1,enumerable:!0,configurable:!0}),Fe.debug(`Preserving HTTP status code ${o} in error for proxy fallback detection`)),f}}}async connectWithStreamableHttp(t){try{console.log("[HttpConnector] Connecting with Streamable HTTP:"),console.log(` Base URL: ${t}`),console.log(` Original URL: ${this.baseUrl}`),console.log(` Gateway URL: ${this.gatewayUrl||"none"}`),console.log(` Auth Provider URL: ${this.opts.authProvider?.serverUrl||"none"}`),console.log(` Headers: ${JSON.stringify(this.headers)}`);const n=new Dre(new URL(t),{authProvider:this.opts.authProvider,requestInit:{headers:this.headers},reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:2}});let r=n;if(this.opts.wrapTransport){const o=this.baseUrl;r=this.opts.wrapTransport(r,o)}const a={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};Fe.debug("Creating Client with capabilities:",JSON.stringify(a.capabilities,null,2)),this.client=new v$(this.clientInfo,a),this.setupRootsHandler(),Fe.debug("Roots handler registered before connect");try{await this.client.connect(r,{timeout:this.timeout});const o=n.sessionId;o?Fe.debug(`Session ID obtained: ${o}`):Fe.warn("Session ID not available after connect - this may cause issues with SSE stream")}catch(o){if(o instanceof Error){const i=o.message||o.toString();if(i.includes("Missing session ID")||i.includes("Bad Request: Missing session ID")||i.includes("Mcp-Session-Id header is required")){const l=new Error(`Session ID error: ${i}. The SDK should automatically extract session ID from initialize response.`);throw l.cause=o,l}}throw o}this.streamableTransport=n,this.connectionManager={stop:ze(async()=>{if(this.streamableTransport)try{await this.streamableTransport.terminateSession(),await this.streamableTransport.close()}catch(o){Fe.warn(`Error closing Streamable HTTP transport: ${o}`)}finally{this.streamableTransport=null}},"stop")},this.connected=!0,this.transportType="streamable-http",this.setupNotificationHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),Fe.debug(`Successfully connected to MCP implementation via streamable HTTP: ${t}`),this.trackConnectorInit({serverUrl:this.baseUrl,publicIdentifier:`${this.baseUrl} (streamable-http)`})}catch(n){throw await this.cleanupResources(),n}}async connectWithSse(t){try{this.connectionManager=new Fre(t,{authProvider:this.opts.authProvider,requestInit:{headers:this.headers}});let n=await this.connectionManager.start();if(this.opts.wrapTransport){const a=this.baseUrl;n=this.opts.wrapTransport(n,a)}const r={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};Fe.debug("Creating Client with capabilities (SSE):",JSON.stringify(r.capabilities,null,2)),this.client=new v$(this.clientInfo,r),this.setupRootsHandler(),Fe.debug("Roots handler registered before connect (SSE)"),await this.client.connect(n),this.connected=!0,this.transportType="sse",this.setupNotificationHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),Fe.debug(`Successfully connected to MCP implementation via HTTP/SSE: ${t}`),this.trackConnectorInit({serverUrl:this.baseUrl,publicIdentifier:`${this.baseUrl} (sse)`})}catch(n){throw await this.cleanupResources(),n}}get publicIdentifier(){return{type:"http",url:this.baseUrl,transport:this.transportType||"unknown"}}getTransportType(){return this.transportType}},ze(_d,"HttpConnector"),_d),lc,Hre=(lc=class extends Ure{static getPackageVersion(){return Sv()}constructor(t){super(t),this._trackClientInit()}_trackClientInit(){const t=Object.keys(this.config.mcpServers??{});rs.getInstance().trackMCPClientInit({codeMode:!1,sandbox:!1,allCallbacks:!1,verify:!1,servers:t,numServers:t.length,isBrowser:!0}).catch(n=>Fe.debug(`Failed to track BrowserMCPClient init: ${n}`))}static fromDict(t){return new lc(t)}createConnectorFromConfig(t){const{url:n,headers:r,authToken:a,authProvider:o,wrapTransport:i,clientOptions:l,onSampling:u,samplingCallback:f,elicitationCallback:m,disableSseFallback:h,preferSse:g,clientInfo:b,gatewayUrl:E,serverId:x}=t;if(!n)throw new Error("Server URL is required");const w=u??f,S={headers:r,authToken:a,authProvider:o,wrapTransport:i,clientOptions:l,onSampling:w,samplingCallback:w,elicitationCallback:m,disableSseFallback:h,preferSse:g,clientInfo:b,gatewayUrl:E,serverId:x};return l?console.log("[BrowserMCPClient] Passing clientOptions to connector:",JSON.stringify(l,null,2)):console.warn("[BrowserMCPClient] No clientOptions provided to connector!"),new Bre(n,S)}},ze(lc,"BrowserMCPClient"),lc);function Du(e){const t=ze(()=>{throw new Error(`Invalid url to pass to open(): ${e}`)},"abort");let n;try{n=new URL(e)}catch{t()}return n.protocol!=="https:"&&n.protocol!=="http:"&&t(),n.hostname!==encodeURIComponent(n.hostname)&&t(),n.username&&(n.username=encodeURIComponent(n.username)),n.password&&(n.password=encodeURIComponent(n.password)),n.pathname=n.pathname.slice(0,1)+encodeURIComponent(n.pathname.slice(1)).replace(/%2f/gi,"/"),n.search=n.search.slice(0,1)+Array.from(n.searchParams.entries()).map(vB).join("&"),n.hash=n.hash.slice(0,1)+encodeURIComponent(n.hash.slice(1)),n.href}ze(Du,"sanitizeUrl");function vB([e,t]){return`${encodeURIComponent(e)}${t.length>0?`=${encodeURIComponent(t)}`:""}`}ze(vB,"sanitizeParam");async function wB(e){return typeof e=="string"?e:e instanceof URLSearchParams||e instanceof FormData?Object.fromEntries(e.entries()):e instanceof Blob?await e.text():e}ze(wB,"serializeBody");var Td,ey=(Td=class{serverUrl;storageKeyPrefix;serverUrlHash;clientName;clientUri;logoUri;callbackUrl;preventAutoAuth;useRedirectFlow;oauthProxyUrl;connectionUrl;originalFetch;onPopupWindow;constructor(t,n={}){this.serverUrl=t,this.storageKeyPrefix=n.storageKeyPrefix||"mcp:auth",this.serverUrlHash=this.hashString(t),this.clientName=n.clientName||"mcp-use",this.clientUri=n.clientUri||(typeof window<"u"?window.location.origin:""),this.logoUri=n.logoUri||"https://mcp-use.com/logo.png",this.callbackUrl=Du(n.callbackUrl||(typeof window<"u"?new URL("/oauth/callback",window.location.origin).toString():"/oauth/callback")),this.preventAutoAuth=n.preventAutoAuth,this.useRedirectFlow=n.useRedirectFlow,this.oauthProxyUrl=n.oauthProxyUrl,this.connectionUrl=n.connectionUrl,this.onPopupWindow=n.onPopupWindow}installFetchInterceptor(){if(!this.oauthProxyUrl){console.warn("[BrowserOAuthProvider] No OAuth proxy URL configured, skipping fetch interceptor installation");return}if(!this.originalFetch)this.originalFetch=window.fetch;else{console.warn("[BrowserOAuthProvider] Fetch interceptor already installed");return}const t=this.oauthProxyUrl,n=this.connectionUrl,r=this.originalFetch;console.log(`[BrowserOAuthProvider] Installing fetch interceptor with proxy: ${t}`),window.fetch=ze(async function(o,i){const l=typeof o=="string"?o:o instanceof URL?o.toString():o.url;if(!(l.includes("/.well-known/")||l.match(/\/(register|token|authorize)$/)))return await r(o,i);try{const f=new URL(l),m=new URL(t);if(f.origin===m.origin&&(f.pathname.startsWith(m.pathname)||l.includes("/inspector/api/oauth")))return await r(o,i)}catch{}try{const f=l.includes("/.well-known/"),m=f?`${t}/metadata?url=${encodeURIComponent(l)}`:`${t}/proxy`;if(console.log(`[OAuth Proxy] Routing ${f?"metadata":"request"} through: ${m}`),f){const E={...i?.headers?Object.fromEntries(new Headers(i.headers)):{}};return n&&(E["X-Connection-URL"]=n),await r(m,{...i,method:"GET",headers:E})}const h=i?.body?await wB(i.body):void 0,b=await(await r(m,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:l,method:i?.method||"POST",headers:i?.headers?Object.fromEntries(new Headers(i.headers)):{},body:h})})).json();return new Response(JSON.stringify(b.body),{status:b.status,statusText:b.statusText,headers:new Headers(b.headers)})}catch(f){return console.error("[OAuth Proxy] Request failed, falling back to direct fetch:",f),await r(o,i)}},"interceptedFetch")}restoreFetch(){this.originalFetch&&(console.log("[BrowserOAuthProvider] Restoring original fetch"),window.fetch=this.originalFetch,this.originalFetch=void 0)}get redirectUrl(){return Du(this.callbackUrl)}get clientMetadata(){return{redirect_uris:[this.redirectUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:this.clientName,client_uri:this.clientUri,logo_uri:this.logoUri}}async clientInformation(){const t=this.getKey("client_info"),n=localStorage.getItem(t);if(n)try{return JSON.parse(n)}catch(r){console.warn(`[${this.storageKeyPrefix}] Failed to parse client information:`,r),localStorage.removeItem(t);return}}async saveClientInformation(t){const n=this.getKey("client_info");localStorage.setItem(n,JSON.stringify(t))}async tokens(){const t=this.getKey("tokens"),n=localStorage.getItem(t);if(n)try{return JSON.parse(n)}catch(r){console.warn(`[${this.storageKeyPrefix}] Failed to parse tokens:`,r),localStorage.removeItem(t);return}}async saveTokens(t){const n=this.getKey("tokens");localStorage.setItem(n,JSON.stringify(t)),localStorage.removeItem(this.getKey("code_verifier")),localStorage.removeItem(this.getKey("last_auth_url"))}async saveCodeVerifier(t){const n=this.getKey("code_verifier");localStorage.setItem(n,t)}async codeVerifier(){const t=this.getKey("code_verifier"),n=localStorage.getItem(t);if(!n)throw new Error(`[${this.storageKeyPrefix}] Code verifier not found in storage for key ${t}. Auth flow likely corrupted or timed out.`);return n}async prepareAuthorizationUrl(t){const n=globalThis.crypto.randomUUID(),r=`${this.storageKeyPrefix}:state_${n}`,a={serverUrlHash:this.serverUrlHash,expiry:Date.now()+1e3*60*10,providerOptions:{serverUrl:this.serverUrl,storageKeyPrefix:this.storageKeyPrefix,clientName:this.clientName,clientUri:this.clientUri,callbackUrl:this.callbackUrl},flowType:this.useRedirectFlow?"redirect":"popup",returnUrl:typeof window<"u"?window.location.href:void 0};console.log(`[OAuth] Storing state key: ${r}`),localStorage.setItem(r,JSON.stringify(a));const o=localStorage.getItem(r);console.log(`[OAuth] State stored successfully: ${!!o}`),t.searchParams.set("state",n);const i=t.toString(),l=Du(i);return localStorage.setItem(this.getKey("last_auth_url"),l),l}async redirectToAuthorization(t){const n=await this.prepareAuthorizationUrl(t);if(this.preventAutoAuth){console.info(`[${this.storageKeyPrefix}] Auto-auth prevented. Authorization URL stored for manual trigger.`);return}if(this.useRedirectFlow){console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL (full-page redirect).`),window.location.href=n;return}const r="width=600,height=700,resizable=yes,scrollbars=yes,status=yes";try{const a=window.open(n,`mcp_auth_${this.serverUrlHash}`,r);this.onPopupWindow&&this.onPopupWindow(n,r,a),!a||a.closed||typeof a.closed>"u"?console.warn(`[${this.storageKeyPrefix}] Popup likely blocked by browser. Manual navigation might be required using the stored URL.`):(a.focus(),console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`))}catch(a){console.error(`[${this.storageKeyPrefix}] Error opening popup window:`,a)}}getLastAttemptedAuthUrl(){const t=localStorage.getItem(this.getKey("last_auth_url"));return t?Du(t):null}clearStorage(){const t=`${this.storageKeyPrefix}_${this.serverUrlHash}_`,n=`${this.storageKeyPrefix}:state_`,r=[];let a=0;for(let i=0;i<localStorage.length;i++){const l=localStorage.key(i);if(l){if(l.startsWith(t))r.push(l);else if(l.startsWith(n))try{const u=localStorage.getItem(l);u&&JSON.parse(u).serverUrlHash===this.serverUrlHash&&r.push(l)}catch(u){console.warn(`[${this.storageKeyPrefix}] Error parsing state key ${l} during clearStorage:`,u)}}}return[...new Set(r)].forEach(i=>{localStorage.removeItem(i),a++}),a}hashString(t){let n=0;for(let r=0;r<t.length;r++){const a=t.charCodeAt(r);n=(n<<5)-n+a,n=n&n}return Math.abs(n).toString(16)}getKey(t){return`${this.storageKeyPrefix}_${this.serverUrlHash}_${t}`}},ze(Td,"BrowserOAuthClientProvider"),Td);async function xN(){const e=new URLSearchParams(window.location.search),t=e.get("code"),n=e.get("state"),r=e.get("error"),a=e.get("error_description"),o="[mcp-callback]";console.log(`${o} Handling callback...`,{code:t,state:n,error:r,errorDescription:a});let i=null,l=null,u=null;try{if(r)throw new Error(`OAuth error: ${r} - ${a||"No description provided."}`);if(!t)throw new Error("Authorization code not found in callback query parameters.");if(!n)throw new Error("State parameter not found or invalid in callback query parameters.");console.log(`[mcp-callback] Looking for state: ${n}`),console.log("[mcp-callback] All localStorage keys:",Object.keys(localStorage));const f=`mcp:auth:state_${n}`;if(localStorage.getItem(f))u=f,console.log(`[mcp-callback] Found state with default key: ${f}`);else{const x=`:state_${n}`;for(let w=0;w<localStorage.length;w++){const S=localStorage.key(w);if(S&&S.endsWith(x)){u=S,console.log(`[mcp-callback] Found state with dynamic key: ${S}`);break}}}if(!u){const x=Object.keys(localStorage).filter(w=>w.includes("state"));throw console.log("[mcp-callback] State keys in storage:",x),new Error(`Invalid or expired state parameter "${n}". No matching state found in storage.`)}const m=localStorage.getItem(u);if(!m)throw new Error(`Invalid or expired state parameter "${n}". No matching state found in storage.`);try{l=JSON.parse(m)}catch{throw new Error("Failed to parse stored OAuth state.")}if(!l.expiry||l.expiry<Date.now())throw localStorage.removeItem(u),new Error("OAuth state has expired. Please try initiating authentication again.");if(!l.providerOptions)throw new Error("Stored state is missing required provider options.");const{serverUrl:h,...g}=l.providerOptions;console.log(`${o} Re-instantiating provider for server: ${h}`),i=new ey(h,g),console.log(`${o} Calling SDK auth() to exchange code...`);const b=new URL(h).origin,E=await Ks(i,{serverUrl:b,authorizationCode:t});if(E==="AUTHORIZED")if(console.log(`${o} Authorization successful via SDK auth().`),l.flowType==="redirect"&&l.returnUrl)console.log(`${o} Redirect flow complete. Returning to: ${l.returnUrl}`),localStorage.removeItem(u),window.location.href=l.returnUrl;else if(window.opener&&!window.opener.closed)console.log(`${o} Popup flow complete. Notifying opener...`),window.opener.postMessage({type:"mcp_auth_callback",success:!0},window.location.origin),localStorage.removeItem(u),window.close();else if(l.returnUrl)console.log(`${o} Popup flow without opener. Returning to: ${l.returnUrl}`),localStorage.removeItem(u),window.location.href=l.returnUrl;else{console.warn(`${o} No opener window or return URL detected. Redirecting to root.`),localStorage.removeItem(u);const w=window.location.pathname.split("/").filter(Boolean),S=w.length>0&&w[w.length-1]==="callback"?"/"+w.slice(0,-2).join("/"):"/";window.location.href=S||"/"}else throw console.warn(`${o} SDK auth() returned unexpected status: ${E}`),new Error(`Unexpected result from authentication library: ${E}`)}catch(f){console.error(`${o} Error during OAuth callback handling:`,f);const m=f instanceof Error?f.message:String(f);window.opener&&!window.opener.closed&&window.opener.postMessage({type:"mcp_auth_callback",success:!1,error:m},window.location.origin);try{document.body.innerHTML="";const h=document.createElement("div");h.style.fontFamily="sans-serif",h.style.padding="20px";const g=document.createElement("h1");g.textContent="Authentication Error",h.appendChild(g);const b=document.createElement("p");b.style.color="red",b.style.backgroundColor="#ffebeb",b.style.border="1px solid red",b.style.padding="10px",b.style.borderRadius="4px",b.textContent=m,h.appendChild(b);const E=document.createElement("p");E.textContent="You can close this window or ";const x=document.createElement("a");if(x.href="#",x.textContent="click here to close",x.onclick=w=>(w.preventDefault(),window.close(),!1),E.appendChild(x),E.appendChild(document.createTextNode(".")),h.appendChild(E),f instanceof Error&&f.stack){const w=document.createElement("pre");w.style.fontSize="0.8em",w.style.color="#555",w.style.marginTop="20px",w.style.whiteSpace="pre-wrap",w.textContent=f.stack,h.appendChild(w)}document.body.appendChild(h)}catch(h){console.error(`${o} Could not display error in callback window:`,h)}u&&localStorage.removeItem(u),i&&(localStorage.removeItem(i.getKey("code_verifier")),localStorage.removeItem(i.getKey("last_auth_url")))}}ze(xN,"onMcpAuthorization");var bE={exports:{}},Bt={};var N$;function Vre(){if(N$)return Bt;N$=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),i=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),f=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),g=Symbol.iterator;function b(P){return P===null||typeof P!="object"?null:(P=g&&P[g]||P["@@iterator"],typeof P=="function"?P:null)}var E={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x=Object.assign,w={};function S(P,H,U){this.props=P,this.context=H,this.refs=w,this.updater=U||E}S.prototype.isReactComponent={},S.prototype.setState=function(P,H){if(typeof P!="object"&&typeof P!="function"&&P!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,P,H,"setState")},S.prototype.forceUpdate=function(P){this.updater.enqueueForceUpdate(this,P,"forceUpdate")};function _(){}_.prototype=S.prototype;function T(P,H,U){this.props=P,this.context=H,this.refs=w,this.updater=U||E}var k=T.prototype=new _;k.constructor=T,x(k,S.prototype),k.isPureReactComponent=!0;var R=Array.isArray;function A(){}var C={H:null,A:null,T:null,S:null},O=Object.prototype.hasOwnProperty;function M(P,H,U){var D=U.ref;return{$$typeof:e,type:P,key:H,ref:D!==void 0?D:null,props:U}}function L(P,H){return M(P.type,H,P.props)}function j(P){return typeof P=="object"&&P!==null&&P.$$typeof===e}function B(P){var H={"=":"=0",":":"=2"};return"$"+P.replace(/[=:]/g,function(U){return H[U]})}var K=/\/+/g;function Z(P,H){return typeof P=="object"&&P!==null&&P.key!=null?B(""+P.key):H.toString(36)}function te(P){switch(P.status){case"fulfilled":return P.value;case"rejected":throw P.reason;default:switch(typeof P.status=="string"?P.then(A,A):(P.status="pending",P.then(function(H){P.status==="pending"&&(P.status="fulfilled",P.value=H)},function(H){P.status==="pending"&&(P.status="rejected",P.reason=H)})),P.status){case"fulfilled":return P.value;case"rejected":throw P.reason}}throw P}function V(P,H,U,D,$){var G=typeof P;(G==="undefined"||G==="boolean")&&(P=null);var W=!1;if(P===null)W=!0;else switch(G){case"bigint":case"string":case"number":W=!0;break;case"object":switch(P.$$typeof){case e:case t:W=!0;break;case m:return W=P._init,V(W(P._payload),H,U,D,$)}}if(W)return $=$(P),W=D===""?"."+Z(P,0):D,R($)?(U="",W!=null&&(U=W.replace(K,"$&/")+"/"),V($,H,U,"",function(me){return me})):$!=null&&(j($)&&($=L($,U+($.key==null||P&&P.key===$.key?"":(""+$.key).replace(K,"$&/")+"/")+W)),H.push($)),1;W=0;var re=D===""?".":D+":";if(R(P))for(var pe=0;pe<P.length;pe++)D=P[pe],G=re+Z(D,pe),W+=V(D,H,U,G,$);else if(pe=b(P),typeof pe=="function")for(P=pe.call(P),pe=0;!(D=P.next()).done;)D=D.value,G=re+Z(D,pe++),W+=V(D,H,U,G,$);else if(G==="object"){if(typeof P.then=="function")return V(te(P),H,U,D,$);throw H=String(P),Error("Objects are not valid as a React child (found: "+(H==="[object Object]"?"object with keys {"+Object.keys(P).join(", ")+"}":H)+"). If you meant to render a collection of children, use an array instead.")}return W}function Y(P,H,U){if(P==null)return P;var D=[],$=0;return V(P,D,"","",function(G){return H.call(U,G,$++)}),D}function F(P){if(P._status===-1){var H=P._result;H=H(),H.then(function(U){(P._status===0||P._status===-1)&&(P._status=1,P._result=U)},function(U){(P._status===0||P._status===-1)&&(P._status=2,P._result=U)}),P._status===-1&&(P._status=0,P._result=H)}if(P._status===1)return P._result.default;throw P._result}var ae=typeof reportError=="function"?reportError:function(P){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var H=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof P=="object"&&P!==null&&typeof P.message=="string"?String(P.message):String(P),error:P});if(!window.dispatchEvent(H))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",P);return}console.error(P)},ee={map:Y,forEach:function(P,H,U){Y(P,function(){H.apply(this,arguments)},U)},count:function(P){var H=0;return Y(P,function(){H++}),H},toArray:function(P){return Y(P,function(H){return H})||[]},only:function(P){if(!j(P))throw Error("React.Children.only expected to receive a single React element child.");return P}};return Bt.Activity=h,Bt.Children=ee,Bt.Component=S,Bt.Fragment=n,Bt.Profiler=a,Bt.PureComponent=T,Bt.StrictMode=r,Bt.Suspense=u,Bt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=C,Bt.__COMPILER_RUNTIME={__proto__:null,c:function(P){return C.H.useMemoCache(P)}},Bt.cache=function(P){return function(){return P.apply(null,arguments)}},Bt.cacheSignal=function(){return null},Bt.cloneElement=function(P,H,U){if(P==null)throw Error("The argument must be a React element, but you passed "+P+".");var D=x({},P.props),$=P.key;if(H!=null)for(G in H.key!==void 0&&($=""+H.key),H)!O.call(H,G)||G==="key"||G==="__self"||G==="__source"||G==="ref"&&H.ref===void 0||(D[G]=H[G]);var G=arguments.length-2;if(G===1)D.children=U;else if(1<G){for(var W=Array(G),re=0;re<G;re++)W[re]=arguments[re+2];D.children=W}return M(P.type,$,D)},Bt.createContext=function(P){return P={$$typeof:i,_currentValue:P,_currentValue2:P,_threadCount:0,Provider:null,Consumer:null},P.Provider=P,P.Consumer={$$typeof:o,_context:P},P},Bt.createElement=function(P,H,U){var D,$={},G=null;if(H!=null)for(D in H.key!==void 0&&(G=""+H.key),H)O.call(H,D)&&D!=="key"&&D!=="__self"&&D!=="__source"&&($[D]=H[D]);var W=arguments.length-2;if(W===1)$.children=U;else if(1<W){for(var re=Array(W),pe=0;pe<W;pe++)re[pe]=arguments[pe+2];$.children=re}if(P&&P.defaultProps)for(D in W=P.defaultProps,W)$[D]===void 0&&($[D]=W[D]);return M(P,G,$)},Bt.createRef=function(){return{current:null}},Bt.forwardRef=function(P){return{$$typeof:l,render:P}},Bt.isValidElement=j,Bt.lazy=function(P){return{$$typeof:m,_payload:{_status:-1,_result:P},_init:F}},Bt.memo=function(P,H){return{$$typeof:f,type:P,compare:H===void 0?null:H}},Bt.startTransition=function(P){var H=C.T,U={};C.T=U;try{var D=P(),$=C.S;$!==null&&$(U,D),typeof D=="object"&&D!==null&&typeof D.then=="function"&&D.then(A,ae)}catch(G){ae(G)}finally{H!==null&&U.types!==null&&(H.types=U.types),C.T=H}},Bt.unstable_useCacheRefresh=function(){return C.H.useCacheRefresh()},Bt.use=function(P){return C.H.use(P)},Bt.useActionState=function(P,H,U){return C.H.useActionState(P,H,U)},Bt.useCallback=function(P,H){return C.H.useCallback(P,H)},Bt.useContext=function(P){return C.H.useContext(P)},Bt.useDebugValue=function(){},Bt.useDeferredValue=function(P,H){return C.H.useDeferredValue(P,H)},Bt.useEffect=function(P,H){return C.H.useEffect(P,H)},Bt.useEffectEvent=function(P){return C.H.useEffectEvent(P)},Bt.useId=function(){return C.H.useId()},Bt.useImperativeHandle=function(P,H,U){return C.H.useImperativeHandle(P,H,U)},Bt.useInsertionEffect=function(P,H){return C.H.useInsertionEffect(P,H)},Bt.useLayoutEffect=function(P,H){return C.H.useLayoutEffect(P,H)},Bt.useMemo=function(P,H){return C.H.useMemo(P,H)},Bt.useOptimistic=function(P,H){return C.H.useOptimistic(P,H)},Bt.useReducer=function(P,H,U){return C.H.useReducer(P,H,U)},Bt.useRef=function(P){return C.H.useRef(P)},Bt.useState=function(P){return C.H.useState(P)},Bt.useSyncExternalStore=function(P,H,U){return C.H.useSyncExternalStore(P,H,U)},Bt.useTransition=function(){return C.H.useTransition()},Bt.version="19.2.3",Bt}var C$;function EN(){return C$||(C$=1,bE.exports=Vre()),bE.exports}var y=EN();const le=Um(y),Ec=QY({__proto__:null,default:le},[y]);function JS(e,t){if(!e)throw new Error(t)}ze(JS,"assert");var R$=3e3,Gre=5e3;function xB(e){return{name:e.name,version:e.version,uri:e.websiteUrl,logo_uri:e.icons?.[0]?.src}}ze(xB,"deriveClientConfigFromClientInfo");function EB(e){const n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("oauth discovery failed")||n.includes("oauth-authorization-server")||n.includes("not valid json")||n.includes("404")&&(n.includes("openid-configuration")||n.includes("oauth-protected-resources")||n.includes("oauth-authorization-url")||n.includes("register"))||n.includes("invalid oauth error response")&&n.includes("not found")}ze(EB,"isOAuthDiscoveryFailure");function SB(e){const{url:t,enabled:n=!0,callbackUrl:r=typeof window<"u"?Du(new URL("/oauth/callback",window.location.origin).toString()):"/oauth/callback",storageKeyPrefix:a="mcp:auth",clientConfig:o={},headers:i,customHeaders:l,proxyConfig:u,autoProxyFallback:f=!0,debug:m=!1,autoRetry:h=!1,autoReconnect:g=R$,transportType:b="auto",preventAutoAuth:E=!0,useRedirectFlow:x=!1,onPopupWindow:w,timeout:S=3e4,sseReadTimeout:_=3e5,wrapTransport:T,onNotification:k,onSampling:R,samplingCallback:A,onElicitation:C}=e,O=i??l??{};l&&!i&&console.warn('[useMcp] The "customHeaders" option is deprecated. Use "headers" instead.');const M=R??A;A&&!R&&console.warn('[useMcp] The "samplingCallback" option is deprecated. Use "onSampling" instead.');const L=y.useMemo(()=>({name:"mcp-use",title:"mcp-use",version:Sv(),description:"mcp-use is a complete TypeScript framework for building and using MCP",icons:[{src:"https://mcp-use.com/logo.png"}],websiteUrl:"https://mcp-use.com"}),[]),j=y.useMemo(()=>e.clientInfo?{...L,...e.clientInfo}:L,[e.clientInfo,L]),B=y.useMemo(()=>xB(j),[j]),K=y.useMemo(()=>o&&Object.keys(o).length>0?(console.warn("[useMcp] The 'clientConfig' option is deprecated and will be removed in a future version. Use 'clientInfo' instead. The clientConfig will be automatically derived from clientInfo."),{...B,...o}):B,[o,B]),Z=y.useMemo(()=>f?typeof f=="boolean"?{enabled:f,proxyAddress:"https://inspector.mcp-use.com/inspector/api/proxy"}:{enabled:f.enabled!==!1,proxyAddress:f.proxyAddress||"https://inspector.mcp-use.com/inspector/api/proxy"}:{enabled:!1,proxyAddress:void 0},[f]),te=y.useRef(!1),[V,Y]=y.useState(u),{gatewayUrl:F,proxyHeaders:ae}=y.useMemo(()=>{const ge=c4(t||"",V);return{gatewayUrl:V?.proxyAddress,proxyHeaders:ge.headers}},[t,V]),ee=y.useMemo(()=>t||"",[t]),P=y.useMemo(()=>({...ae,...O}),[ae,O]),[H,U]=y.useState("discovering"),[D,$]=y.useState([]),[G,W]=y.useState([]),[re,pe]=y.useState([]),[me,ne]=y.useState([]),[J,X]=y.useState(),[se,he]=y.useState(),[Te,Be]=y.useState(void 0),[$e,Ge]=y.useState([]),[dt,Ve]=y.useState(void 0),[ct,rt]=y.useState(void 0),Ee=y.useRef(null),Ce=y.useRef(null),He=y.useRef(null),st=y.useRef(!1),Je=y.useRef(!0),it=y.useRef(0),kt=y.useRef(null),Nn=y.useRef(!1),ot=y.useRef(H),zn=y.useRef(g),qt=y.useRef(null),Ye=y.useRef(null),We=y.useRef(null);y.useEffect(()=>{ot.current=H,zn.current=g},[H,g]);const ue=y.useCallback((ge,_e,...Ne)=>{const Ae=Ne.length>0?`${_e} ${Ne.map(Pe=>JSON.stringify(Pe)).join(" ")}`:_e;console[ge](`[useMcp] ${Ae}`),Je.current&&Ge(Pe=>[...Pe.slice(-100),{level:ge,message:Ae,timestamp:Date.now()}])},[]),It=y.useCallback(async(ge=!1)=>{if(ge||ue("info","Disconnecting..."),st.current=!1,kt.current&&clearTimeout(kt.current),kt.current=null,Ee.current)try{const _e="inspector-server",Ne=Ee.current.getSession(_e);Ne&&Ne._healthCheckCleanup&&(Ne._healthCheckCleanup(),Ne._healthCheckCleanup=null),Ne&&await Ee.current.closeSession(_e)}catch(_e){ge||ue("warn","Error closing session:",_e)}Ee.current=null,Je.current&&!ge&&(U("discovering"),$([]),W([]),pe([]),ne([]),Be(void 0),Ve(void 0))},[ue]),Nt=y.useCallback((ge,_e)=>{ue("error",ge,_e??"");const Ne=_e&&"code"in _e?_e.code:void 0,Ae=Z.enabled&&!V?.proxyAddress,Pe=ge.includes("CORS")||ge.includes("blocked by CORS policy")||ge.includes("Failed to fetch"),Ze=Ne===400,qe=typeof Ne=="number"&&Ne>=404&&Ne<500;if(Ae&&(Pe||Ze||qe)&&!(Ne===401||Ne===403))return ue("info",`Direct connection failed with ${Pe?"CORS error":Ze?"HTTP 400 (Bad Request)":"HTTP 4xx error"}. Trying with proxy...`),Ee.current=null,Ce.current=null,ue("debug","Cleared client and auth provider for proxy fallback"),Y({proxyAddress:Z.proxyAddress}),Je.current&&U("discovering"),setTimeout(()=>{Je.current&&Ye.current?.()},1e3),!0;if(Je.current){console.log("[useMcp] Setting state to FAILED:",ge),U("failed"),Be(ge);const tt=Ce.current?.getLastAttemptedAuthUrl();tt&&(Ve(tt),ue("info","Manual authentication URL may be available.",tt))}return st.current=!1,t&&rs.getInstance().trackUseMcpConnection({url:t,transportType:b,success:!1,errorType:_e?.name||"UnknownError",hasOAuth:!!Ce.current,hasSampling:!!M,hasElicitation:!!C}).catch(()=>{}),!1},[ue,t,b,M,C,Z,V]),jt=y.useCallback(async()=>{if(!n||!t){ue("debug",n?"No server URL provided, skipping connection.":"Connection disabled via enabled flag.");return}if(st.current){ue("debug","Connection attempt already in progress.");return}if(!Je.current){ue("debug","Connect called after unmount, aborting.");return}if(st.current=!0,it.current+=1,Be(void 0),Ve(void 0),qt.current=null,U("discovering"),ue("info",`Connecting attempt #${it.current} to ${t}...`),!Ce.current){let Ne;if(F){const Ae=new URL(F),Pe=Ae.pathname.replace(/\/proxy\/?$/,"");Ne=`${Ae.origin}${Pe}/oauth`,ue("debug",`OAuth proxy URL derived from gateway: ${Ne}`)}Ce.current=new ey(ee,{storageKeyPrefix:a,clientName:K.name,clientUri:K.uri,logoUri:K.logo_uri||"https://mcp-use.com/logo.png",callbackUrl:r,preventAutoAuth:E,useRedirectFlow:x,oauthProxyUrl:Ne,onPopupWindow:w}),ue("debug",`BrowserOAuthClientProvider initialized with URL: ${ee}, proxy: ${Ne?"enabled":"disabled"}, gateway: ${F?"enabled":"disabled"}`),Ne&&(Ce.current.installFetchInterceptor(),ue("debug","Installed OAuth fetch interceptor"))}Ee.current?ue("debug","BrowserMCPClient already exists, reusing."):(Ee.current=new Hre,ue("debug","BrowserMCPClient initialized in connect."));const ge=ze(async(Ne,Ae=!1)=>{if(!Je.current)return ue("debug","Connection attempt aborted - component unmounted"),"failed";ue("info",`Attempting connection with transport: ${Ne}`),ue("debug",`Client ref status at start of tryConnectWithTransport: ${Ee.current?"initialized":"NULL"}`);try{const Pe="inspector-server",Ze={url:t,transport:Ne==="sse"?"http":Ne,disableSseFallback:b==="http",preferSse:Ne==="sse",clientInfo:j};if(F&&(Ze.gatewayUrl=F,console.log(`[useMcp] Using proxy gateway: ${F} for target: ${t}`)),P&&Object.keys(P).length>0&&(Ze.headers=P),Ce.current){const Qe=await Ce.current.tokens();if(!Je.current)return ue("debug","Connection aborted after token fetch - component unmounted"),"failed";Qe?.access_token&&(Ze.headers={...Ze.headers,Authorization:`Bearer ${Qe.access_token}`})}if(!Ee.current){if(!Je.current)return ue("debug","Connection aborted - component unmounted, client cleaned up"),"failed";const Qe=new Error("Client not initialized - this is a bug in the connection flow");throw ue("error","Client ref is null in tryConnectWithTransport but component is still mounted"),Qe}Ee.current.addServer(Pe,{...Ze,authProvider:Ce.current,clientOptions:K,onSampling:M,samplingCallback:M,elicitationCallback:C,wrapTransport:T?Qe=>(console.log("[useMcp] Applying transport wrapper for server:",Pe,"url:",t),T(Qe,t)):void 0});const qe=await Ee.current.createSession(Pe,!1);if(!Je.current)return ue("debug","Connection aborted after session creation - component unmounted"),"failed";if(qe.on("notification",Qe=>{k?.(Qe),Qe.method==="notifications/tools/list_changed"?(ue("info","Tools list changed, auto-refreshing..."),Ln().catch(Ke=>ue("warn","Auto-refresh tools failed:",Ke))):Qe.method==="notifications/resources/list_changed"?(ue("info","Resources list changed, auto-refreshing..."),sn().catch(Ke=>ue("warn","Auto-refresh resources failed:",Ke))):Qe.method==="notifications/prompts/list_changed"&&(ue("info","Prompts list changed, auto-refreshing..."),Mn().catch(Ke=>ue("warn","Auto-refresh prompts failed:",Ke)))}),await qe.initialize(),!Je.current)return ue("debug","Connection completed but component unmounted, aborting"),"failed";if(ue("info","✅ Successfully connected to MCP server"),ue("info","Server info:",qe.connector.serverInfo),ue("info","Server capabilities:",qe.connector.serverCapabilities),console.log("[useMcp] Server info:",qe.connector.serverInfo),console.log("[useMcp] Server capabilities:",qe.connector.serverCapabilities),!Je.current)return ue("debug","Skipping state update - component unmounted"),"failed";U("ready"),qt.current=Ne;const et=ze(()=>{let Qe=null,Ke=Date.now();const St=1e4,En=3e4;return Qe=setInterval(ze(async()=>{if(!Je.current||ot.current!=="ready"){Qe&&(clearInterval(Qe),Qe=null);return}try{await qe.connector.listTools(),Ke=Date.now()}catch{const _t=Date.now()-Ke;_t>En&&(ue("warn",`Connection appears to be broken (no response for ${Math.round(_t/1e3)}s), attempting to reconnect...`),Qe&&(clearInterval(Qe),Qe=null),zn.current&&Je.current&&(U("discovering"),ue("info","Auto-reconnecting to MCP server..."),setTimeout(()=>{Je.current&&ot.current==="discovering"&&jt()},typeof zn.current=="number"?zn.current:R$)))}},"checkConnectionHealth"),St),()=>{Qe&&(clearInterval(Qe),Qe=null)}},"setupConnectionMonitoring");if(g){const Qe=et();qe._healthCheckCleanup=Qe}rs.getInstance().trackUseMcpConnection({url:t,transportType:Ne,success:!0,hasOAuth:!!Ce.current,hasSampling:!!M,hasElicitation:!!C}).catch(()=>{}),$(qe.connector.tools||[]);const Ut=await qe.connector.listAllResources();if(!Je.current)return ue("debug","Connection aborted after listing resources - component unmounted"),"failed";W(Ut.resources||[]);const tt=await qe.connector.listPrompts();if(!Je.current)return ue("debug","Connection aborted after listing prompts - component unmounted"),"failed";ne(tt.prompts||[]);const xt=qe.connector.serverInfo,Ct=qe.connector.serverCapabilities;if(xt){if(console.log("[useMcp] Server info:",xt),!Je.current)return ue("debug","Skipping state update - component unmounted"),"failed";X(xt);const Qe=(async()=>{try{const Ke=xt.icons;if(Ke&&Array.isArray(Ke)&&Ke.length>0){const St=Ke[0].src||Ke[0].url;if(St){ue("info","Server provided icon:",St);const ht=await(await fetch(St)).blob(),Fn=await new Promise((_t,Cn)=>{const en=new FileReader;en.onloadend=()=>_t(en.result),en.onerror=Cn,en.readAsDataURL(ht)});return Je.current&&(X(_t=>_t?{..._t,icon:Fn}:void 0),ue("debug","Server icon converted to base64")),Fn}}if(t){const St=await l4(t);if(!Je.current)return ue("debug","Connection aborted after favicon detection - component unmounted"),null;if(St)return X(En=>En?{...En,icon:St}:void 0),ue("debug","Favicon detected and added to serverInfo"),St}return null}catch(Ke){return ue("debug","Icon loading failed (non-critical):",Ke),null}})();He.current=Qe}if(Ct){if(console.log("[useMcp] Server capabilities:",Ct),!Je.current)return ue("debug","Skipping state update - component unmounted"),"failed";he(Ct)}if(Ce.current){const Qe=await Ce.current.tokens();if(!Je.current)return ue("debug","Connection aborted after token fetch for auth tokens - component unmounted"),"failed";if(Qe?.access_token){const Ke=Qe.expires_in?Date.now()+Qe.expires_in*1e3:void 0;if(!Je.current)return ue("debug","Skipping state update - component unmounted"),"failed";rt({access_token:Qe.access_token,token_type:Qe.token_type||"Bearer",expires_at:Ke,refresh_token:Qe.refresh_token,scope:Qe.scope})}}return"success"}catch(Pe){const Ze=Pe,qe=Ze?.message||String(Pe),et=EB(Pe),Ut=Ze.code===401||qe.includes("401")||qe.includes("Unauthorized");if(et&&O&&Object.keys(O).length>0)return Nt("Authentication failed (HTTP 401). Server does not support OAuth. Check your Authorization header value is correct."),"failed";if(Ut){if(et)return Nt("Authentication required (HTTP 401). Server does not support OAuth. Add an Authorization header in the Custom Headers section (e.g., Authorization: Bearer YOUR_API_KEY)."),"failed";if(Ce.current){if(ue("info","Authentication required. OAuth provider available."),ue("info","Waiting for user to initiate authentication flow..."),Je.current){U("pending_auth");const xt=Ce.current?.getLastAttemptedAuthUrl();xt&&(Ve(xt),ue("info","Retrieved stored auth URL for manual authentication"))}return st.current=!1,"auth_redirect"}return O&&Object.keys(O).length>0?(Nt("Authentication failed: Server returned 401 Unauthorized. Check your Authorization header value is correct."),"failed"):(Nt("Authentication required: Server returned 401 Unauthorized. Add an Authorization header in the Custom Headers section (e.g., Authorization: Bearer YOUR_API_KEY)."),"failed")}return Nt(qe,Ze instanceof Error?Ze:new Error(String(Ze)))?"auth_redirect":"failed"}},"tryConnectWithTransport");let _e="failed";if(b==="sse")ue("debug","Using SSE-only transport mode"),_e=await ge("sse");else if(b==="http")ue("debug","Using HTTP-only transport mode"),_e=await ge("http");else{ue("debug","Using auto transport mode (HTTP with SSE fallback)");const Ne=await ge("http");Ne==="fallback"&&Je.current&&ot.current!=="authenticating"?(ue("info","HTTP failed, attempting SSE fallback..."),_e=await ge("sse")):_e=Ne}(_e==="success"||_e==="failed"||_e==="auth_redirect")&&(st.current=!1),ue("debug",`Connection sequence finished with status: ${_e}`)},[ue,Nt,It,t,a,r,K.name,K.version,K.uri,K.logo_uri,O,b,E,x,w,n,S,_,j,F,P,ee]);y.useEffect(()=>{Ye.current=jt,We.current=Nt},[jt,Nt]);const Pt=y.useCallback(async(ge,_e,Ne)=>{if(ot.current!=="ready"||!Ee.current)throw new Error(`MCP client is not ready (current state: ${H}). Cannot call tool "${ge}".`);ue("info",`Calling tool: ${ge}`,_e);const Ae=Date.now();try{const Ze=Ee.current.getSession("inspector-server");if(!Ze)throw new Error("No active session found");const qe=await Ze.connector.callTool(ge,_e||{},Ne);return ue("info",`Tool "${ge}" call successful:`,qe),rs.getInstance().trackUseMcpToolCall({toolName:ge,success:!0,executionTimeMs:Date.now()-Ae}).catch(()=>{}),qe}catch(Pe){throw ue("error",`Tool "${ge}" call failed:`,Pe),rs.getInstance().trackUseMcpToolCall({toolName:ge,success:!1,errorType:Pe instanceof Error?Pe.name:"UnknownError",executionTimeMs:Date.now()-Ae}).catch(()=>{}),Pe}},[H]),Xt=y.useCallback(()=>{ot.current==="failed"?(ue("info","Retry requested..."),Ye.current?.()):ue("warn",`Retry called but state is not 'failed' (state: ${ot.current}). Ignoring.`)},[ue]),xn=y.useCallback(async()=>{ue("info","Manual authentication requested...");const ge=ot.current;if(ge==="failed")ue("info","Attempting to reconnect and authenticate via retry..."),Xt();else if(ge==="pending_auth"){ue("info","Proceeding with authentication from pending state...");try{JS(Ce.current,"Auth Provider not available for manual auth"),JS(t,"Server URL is required for authentication"),ue("info","Initiating OAuth flow (preserving existing state)..."),U("authenticating");let _e;if(F){const qe=new URL(F),et=qe.pathname.replace(/\/proxy\/?$/,"");_e=`${qe.origin}${et}/oauth`}const Ne=new ey(ee,{storageKeyPrefix:a,clientName:K.name,clientUri:K.uri,logoUri:K.logo_uri||"https://mcp-use.com/logo.png",callbackUrl:r,preventAutoAuth:!1,useRedirectFlow:x,oauthProxyUrl:_e,onPopupWindow:w});_e&&!F?(Ne.installFetchInterceptor(),ue("info","Installed OAuth fetch interceptor for manual auth")):_e&&F&&ue("info","Using MCP gateway proxy for OAuth (no fetch interceptor needed)"),Ce.current=Ne,ue("info","Triggering fresh OAuth authorization...");const{auth:Ae}=await Ua(async()=>{const{auth:qe}=await Promise.resolve().then(()=>kre);return{auth:qe}},void 0),Pe=new URL(t).origin;try{await Ae(Ne,{serverUrl:Pe}),ue("info","OAuth flow completed (tokens obtained)")}catch(qe){ue("info","OAuth flow initiated (popup/redirect):",qe instanceof Error?qe.message:"Redirecting...")}const Ze=Ne.getLastAttemptedAuthUrl();Ze&&(Ve(Ze),ue("info","Updated auth URL for fallback:",Ze))}catch(_e){if(!Je.current)return;U("pending_auth"),ue("error",`Manual authentication failed: ${_e instanceof Error?_e.message:String(_e)}`)}}else if(ge==="authenticating"){ue("warn","Already attempting authentication. Check for blocked popups or wait for timeout.");const _e=Ce.current?.getLastAttemptedAuthUrl();_e&&!dt&&(Ve(_e),ue("info","Manual authentication URL retrieved:",_e))}else ue("info",`Client not in a state requiring manual authentication trigger (state: ${ge}). If needed, try disconnecting and reconnecting.`)},[ue,Xt,dt,t,x,w,a,K.name,K.uri,K.logo_uri,r,j]),ut=y.useCallback(()=>{if(Ce.current){const ge=Ce.current.clearStorage();ue("info",`Cleared ${ge} item(s) from localStorage for ${t}.`),Ve(void 0),It()}else ue("warn","Auth provider not initialized, cannot clear storage.")},[t,ue,It]),$t=y.useCallback(async()=>{if(ot.current!=="ready"||!Ee.current)throw new Error(`MCP client is not ready (current state: ${H}). Cannot list resources.`);ue("info","Listing resources");try{const _e=Ee.current.getSession("inspector-server");if(!_e)throw new Error("No active session found");const Ne=await _e.connector.listAllResources();W(Ne.resources||[]),ue("info","Resources listed successfully")}catch(ge){throw ue("error","List resources failed:",ge),ge}},[H]),Ht=y.useCallback(async ge=>{if(ot.current!=="ready"||!Ee.current)throw new Error(`MCP client is not ready (current state: ${H}). Cannot read resource.`);ue("info",`Reading resource: ${ge}`);try{const Ne=Ee.current.getSession("inspector-server");if(!Ne)throw new Error("No active session found");const Ae=await Ne.connector.readResource(ge);return ue("info","Resource read successful:",Ae),rs.getInstance().trackUseMcpResourceRead({resourceUri:ge,success:!0}).catch(()=>{}),Ae}catch(_e){throw ue("error","Resource read failed:",_e),rs.getInstance().trackUseMcpResourceRead({resourceUri:ge,success:!1,errorType:_e instanceof Error?_e.name:"UnknownError"}).catch(()=>{}),_e}},[H]),zt=y.useCallback(async()=>{if(ot.current!=="ready"||!Ee.current)throw new Error(`MCP client is not ready (current state: ${H}). Cannot list prompts.`);ue("info","Listing prompts");try{const _e=Ee.current.getSession("inspector-server");if(!_e)throw new Error("No active session found");const Ne=await _e.connector.listPrompts();ne(Ne.prompts||[]),ue("info","Prompts listed successfully")}catch(ge){throw ue("error","List prompts failed:",ge),ge}},[H]),Ln=y.useCallback(async()=>{if(ot.current!=="ready"||!Ee.current){ue("debug","Cannot refresh tools - client not ready");return}ue("debug","Refreshing tools list");try{const _e=Ee.current.getSession("inspector-server");if(!_e){ue("warn","No active session found for tools refresh");return}const Ne=await _e.connector.listTools();$(Ne||[]),ue("info","Tools list refreshed successfully")}catch(ge){ue("warn","Failed to refresh tools:",ge)}},[ue]),sn=y.useCallback(async()=>{if(ot.current!=="ready"||!Ee.current){ue("debug","Cannot refresh resources - client not ready");return}ue("debug","Refreshing resources list");try{const _e=Ee.current.getSession("inspector-server");if(!_e){ue("warn","No active session found for resources refresh");return}const Ne=await _e.connector.listAllResources();W(Ne.resources||[]),ue("info","Resources list refreshed successfully")}catch(ge){ue("warn","Failed to refresh resources:",ge)}},[ue]),Mn=y.useCallback(async()=>{if(ot.current!=="ready"||!Ee.current){ue("debug","Cannot refresh prompts - client not ready");return}ue("debug","Refreshing prompts list");try{const _e=Ee.current.getSession("inspector-server");if(!_e){ue("warn","No active session found for prompts refresh");return}const Ne=await _e.connector.listPrompts();ne(Ne.prompts||[]),ue("info","Prompts list refreshed successfully")}catch(ge){ue("warn","Failed to refresh prompts:",ge)}},[ue]),qn=y.useCallback(async()=>{ue("info","Refreshing all lists (tools, resources, prompts)"),await Promise.all([Ln(),sn(),Mn()])},[Ln,sn,Mn,ue]),oe=y.useCallback(async(ge,_e)=>{if(ot.current!=="ready"||!Ee.current)throw new Error(`MCP client is not ready (current state: ${H}). Cannot get prompt.`);ue("info",`Getting prompt: ${ge}`,_e);try{const Ae=Ee.current.getSession("inspector-server");if(!Ae)throw new Error("No active session found");const Pe=await Ae.connector.getPrompt(ge,_e||{});return ue("info",`Prompt "${ge}" retrieved successfully:`,Pe),Pe}catch(Ne){throw ue("error",`Prompt "${ge}" retrieval failed:`,Ne),Ne}},[H]);y.useEffect(()=>{const ge=ze(_e=>{_e.origin===window.location.origin&&_e.data?.type==="mcp_auth_callback"&&(ue("info","Received auth callback message.",_e.data),kt.current&&clearTimeout(kt.current),kt.current=null,_e.data.success?(ue("info","Authentication successful via popup. Reconnecting client..."),st.current&&ue("debug","Connection attempt already in progress, resetting flag to allow reconnection."),st.current=!1,setTimeout(()=>{Je.current&&(ue("debug","Initiating reconnection after successful auth callback."),Ye.current?.())},100)):We.current?.(`Authentication failed in callback: ${_e.data.error||"Unknown reason."}`))},"messageHandler");return window.addEventListener("message",ge),ue("debug","Auth callback message listener added."),()=>{window.removeEventListener("message",ge),ue("debug","Auth callback message listener removed."),kt.current&&clearTimeout(kt.current)}},[ue]),y.useEffect(()=>{te.current=!1,Y(u)},[t,u]),y.useEffect(()=>{if(Je.current=!0,!n||!t)return ue("debug",n?"No server URL provided, skipping connection.":"Connection disabled via enabled flag."),U("discovering"),()=>{Je.current=!1};if(ue("debug","useMcp mounted, initiating connection."),it.current=0,!Ce.current||Ce.current.serverUrl!==ee){let ge;if(F){const _e=new URL(F),Ne=_e.pathname.replace(/\/proxy\/?$/,"");ge=`${_e.origin}${Ne}/oauth`,ue("debug",`OAuth proxy URL derived from gateway: ${ge}`)}Ce.current=new ey(ee,{storageKeyPrefix:a,clientName:K.name,clientUri:K.uri,logoUri:K.logo_uri||"https://mcp-use.com/logo.png",callbackUrl:r,preventAutoAuth:E,useRedirectFlow:x,oauthProxyUrl:ge,onPopupWindow:w}),ue("debug",`BrowserOAuthClientProvider initialized/updated with URL: ${ee}, proxy: ${ge?"enabled":"disabled"}, gateway: ${F?"enabled":"disabled"}`),ge&&(Ce.current.installFetchInterceptor(),ue("debug","Installed OAuth fetch interceptor"))}return jt(),()=>{if(Je.current=!1,ue("debug","useMcp unmounting, disconnecting."),(ot.current==="authenticating"||ot.current==="pending_auth")&&Ce.current)try{const ge=Ce.current.clearStorage();ge>0&&ue("debug",`Cleared ${ge} OAuth state item(s) during unmount to prevent corruption`)}catch(ge){ue("debug","Error clearing OAuth state during unmount:",ge)}It(!0)}},[t,n,a,r,K.name,K.version,K.uri,K.logo_uri,x,j,ee]);const ce=y.useRef(Xt),ye=y.useRef(ue);y.useEffect(()=>{ce.current=Xt,ye.current=ue},[Xt,ue]),y.useEffect(()=>{let ge=null;if(H==="failed"&&h&&it.current>0){if(!Nn.current){Nn.current=!0;const _e=typeof h=="number"?h:Gre;ye.current("info",`Connection failed, auto-retrying in ${_e}ms...`),ge=setTimeout(()=>{Nn.current=!1,Je.current&&ot.current==="failed"&&ce.current()},_e)}}else H!=="failed"&&(Nn.current=!1);return()=>{ge&&(clearTimeout(ge),Nn.current=!1)}},[H,h]);const ke=y.useCallback(async()=>ot.current!=="ready"?(ue("warn","Cannot ensure icon loaded - not connected"),null):J?.icon?J.icon:He.current?(ue("debug","Waiting for icon to finish loading..."),await He.current):(ue("debug","No icon available and no loading in progress"),null),[J,ue]);return{state:H,name:J?.name||t||"",tools:D,resources:G,resourceTemplates:re,prompts:me,serverInfo:J,capabilities:se,error:Te,log:$e,authUrl:dt,authTokens:ct,client:Ee.current,callTool:Pt,readResource:Ht,listResources:$t,listPrompts:zt,getPrompt:oe,refreshTools:Ln,refreshResources:sn,refreshPrompts:Mn,refreshAll:qn,retry:Xt,disconnect:It,authenticate:xn,clearStorage:ut,ensureIconLoaded:ke}}ze(SB,"useMcp");var Nd,Wre=(Nd=class extends le.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("Widget Error:",t,n)}render(){return this.state.hasError?le.createElement("div",{className:"p-4 border border-red-500 bg-red-50 text-red-900 rounded-md dark:bg-red-900/20 dark:text-red-100"},le.createElement("h3",{className:"font-bold mb-2"},"Widget Error"),le.createElement("pre",{className:"text-sm whitespace-pre-wrap"},this.state.error?.message)):this.props.children}},ze(Nd,"ErrorBoundary"),Nd),$p="openai:set_globals";function Mo(e){return y.useSyncExternalStore(t=>{const n=ze(r=>{r.detail.globals[e]!==void 0&&t()},"handleSetGlobal");return typeof window<"u"&&window.addEventListener($p,n),()=>{typeof window<"u"&&window.removeEventListener($p,n)}},()=>typeof window<"u"&&window.openai?window.openai[e]:void 0)}ze(Mo,"useOpenAiGlobal");function Xd(e){const[t,n]=y.useState(()=>typeof window<"u"&&!!window.openai);y.useEffect(()=>{if(typeof window<"u"&&window.openai){n(!0);return}const L=setInterval(()=>{typeof window<"u"&&window.openai&&(n(!0),clearInterval(L))},100),j=ze(()=>{typeof window<"u"&&window.openai&&(n(!0),clearInterval(L))},"handleSetGlobals");typeof window<"u"&&window.addEventListener($p,j);const B=setTimeout(()=>{clearInterval(L),typeof window<"u"&&window.removeEventListener($p,j)},5e3);return()=>{clearInterval(L),clearTimeout(B),typeof window<"u"&&window.removeEventListener($p,j)}},[]);const r=y.useMemo(()=>t?"openai":"mcp-ui",[t]),a=typeof window<"u"?window.location.search:"",o=y.useMemo(()=>{const L=new URLSearchParams(a);return L.has("mcpUseParams")?JSON.parse(L.get("mcpUseParams")):{toolInput:{},toolOutput:{},toolId:""}},[a]),i=r==="openai"?Mo("toolInput"):o.toolInput,l=r==="openai"?Mo("toolOutput"):o.toolOutput,u=Mo("toolResponseMetadata"),f=y.useMemo(()=>{if(u&&typeof u=="object"){const L=u["mcp-use/props"];if(L)return L}return e||{}},[u,e]),m=Mo("widgetState"),h=Mo("theme"),g=Mo("displayMode"),b=Mo("safeArea"),E=Mo("maxHeight"),x=Mo("userAgent"),w=Mo("locale"),S=y.useMemo(()=>typeof window<"u"&&window.__mcpPublicUrl?window.__mcpPublicUrl.replace(/\/mcp-use\/public$/,""):"",[]),[_,T]=y.useState(null);y.useEffect(()=>{m!==void 0&&T(m)},[m]);const k=y.useCallback(async(L,j)=>{if(!window.openai?.callTool)throw new Error("window.openai.callTool is not available");return window.openai.callTool(L,j)},[]),R=y.useCallback(async L=>{if(!window.openai?.sendFollowUpMessage)throw new Error("window.openai.sendFollowUpMessage is not available");return window.openai.sendFollowUpMessage({prompt:L})},[]),A=y.useCallback(L=>{if(!window.openai?.openExternal)throw new Error("window.openai.openExternal is not available");window.openai.openExternal({href:L})},[]),C=y.useCallback(async L=>{if(!window.openai?.requestDisplayMode)throw new Error("window.openai.requestDisplayMode is not available");return window.openai.requestDisplayMode({mode:L})},[]),O=y.useCallback(async L=>{if(!window.openai?.setWidgetState)throw new Error("window.openai.setWidgetState is not available");const B=typeof L=="function"?L(m!==void 0?m:_):L;return T(B),window.openai.setWidgetState(B)},[m,_]),M=y.useMemo(()=>r==="openai"&&u===null,[r,u]);return{props:f,toolInput:i||{},output:l??null,metadata:u??null,state:_,setState:O,theme:h||"light",displayMode:g||"inline",safeArea:b||{insets:{top:0,bottom:0,left:0,right:0}},maxHeight:E||600,userAgent:x||{device:{type:"desktop"},capabilities:{hover:!0,touch:!1}},locale:w||"en",mcp_url:S,callTool:k,sendFollowUpMessage:R,openExternal:A,requestDisplayMode:C,isAvailable:t,isPending:M}}ze(Xd,"useWidget");function Kre(e){const{props:t}=Xd(e);return t}ze(Kre,"useWidgetProps");function Yre(){const{theme:e}=Xd();return e}ze(Yre,"useWidgetTheme");function Zre(e){const{state:t,setState:n}=Xd();return y.useEffect(()=>{t===null&&e!==void 0&&window.openai?.setWidgetState&&n(e)},[]),[t,n]}ze(Zre,"useWidgetState");var k$=ze(({children:e})=>{const{theme:t,isAvailable:n}=Xd();console.log("theme",t);const[r,a]=y.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");y.useEffect(()=>{if(typeof window>"u")return;const i=window.matchMedia("(prefers-color-scheme: dark)"),l=ze(u=>{a(u.matches?"dark":"light")},"handleChange");return i.addEventListener("change",l),()=>i.removeEventListener("change",l)},[]);const o=n?t:r;return y.useLayoutEffect(()=>{typeof document>"u"||(o==="dark"?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark"))},[o]),le.createElement(le.Fragment,null,e)},"ThemeProvider");function _B({children:e,className:t="",position:n="top-right",attachTo:r,showLabels:a=!0,debugger:o=!1,viewControls:i=!1}){const{props:l,output:u,metadata:f,state:m,theme:h,displayMode:g,safeArea:b,maxHeight:E,userAgent:x,locale:w,isAvailable:S,callTool:_,sendFollowUpMessage:T,openExternal:k,requestDisplayMode:R,setState:A}=Xd(),[C,O]=y.useState(!1),[M,L]=y.useState(!1),j=y.useRef(null),B=y.useRef(null),[K,Z]=y.useState([]),[te,V]=y.useState(""),[Y,F]=y.useState("get-my-city"),[ae,ee]=y.useState("{}"),[P,H]=y.useState("Test follow-up message"),[U,D]=y.useState("https://docs.mcp-use.com"),$=g==="fullscreen"&&S,G=g==="pip"&&S,W=typeof window<"u"&&window.location.pathname.includes("/inspector/api/");y.useEffect(()=>{const Ee=setTimeout(()=>{if(typeof window<"u"&&window.openai)try{const Ce=Object.keys(window.openai);Z(Ce)}catch{Z([])}else Z([])},100);return()=>{clearTimeout(Ee)}},[]);const re=h==="dark",pe=ze(()=>{const Ee=["absolute","z-[1000]","flex","gap-2","transition-opacity","duration-200","ease-in-out",C?"opacity-100":"opacity-0",C?"pointer-events-auto":"pointer-events-none"];switch(n){case"top-left":return[...Ee,"top-4","left-4"];case"top-center":return[...Ee,"top-4","left-1/2","-translate-x-1/2"];case"top-right":return[...Ee,"top-4","right-4"];case"center-left":return[...Ee,"top-1/2","left-4","-translate-y-1/2"];case"center-right":return[...Ee,"top-1/2","right-4","-translate-y-1/2"];case"bottom-left":return[...Ee,"bottom-4","left-4"];case"bottom-center":return[...Ee,"bottom-4","left-1/2","-translate-x-1/2"];case"bottom-right":return[...Ee,"bottom-4","right-4"];default:return[...Ee,"top-4","right-4"]}},"getPositionClasses"),me=ze(()=>{const Ce=b?.insets?.top?Math.max(16,b.insets.top+8):16,He=b?.insets?.right?Math.max(16,b.insets.right+8):16,st=b?.insets?.bottom?Math.max(16,b.insets.bottom+8):16,Je=b?.insets?.left?Math.max(16,b.insets.left+8):16,it={};switch(n){case"top-left":it.top=`${Ce}px`,it.left=`${Je}px`;break;case"top-center":it.top=`${Ce}px`;break;case"top-right":it.top=`${Ce}px`,it.right=`${He}px`;break;case"center-left":it.left=`${Je}px`;break;case"center-right":it.right=`${He}px`;break;case"bottom-left":it.bottom=`${st}px`,it.left=`${Je}px`;break;case"bottom-center":it.bottom=`${st}px`;break;case"bottom-right":it.bottom=`${st}px`,it.right=`${He}px`;break;default:it.top=`${Ce}px`,it.right=`${He}px`;break}return it},"getPositionOffsetStyles");y.useEffect(()=>{if(!r)return;const Ee=ze(()=>O(!0),"handleMouseEnter"),Ce=ze(()=>O(!1),"handleMouseLeave");return r.addEventListener("mouseenter",Ee),r.addEventListener("mouseleave",Ce),()=>{r.removeEventListener("mouseenter",Ee),r.removeEventListener("mouseleave",Ce)}},[r]),y.useEffect(()=>{if(!M)return;const Ee=ze(Ce=>{B.current&&!B.current.contains(Ce.target)&&L(!1)},"handleClickOutside");return document.addEventListener("mousedown",Ee),()=>{document.removeEventListener("mousedown",Ee)}},[M]),y.useEffect(()=>(M?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[M]);const ne=ze(()=>{L(!M)},"handleToggleOverlay"),J=ze(async()=>{try{V("Calling tool...");const Ee=ae.trim()?JSON.parse(ae):{},Ce=await _(Y,Ee);V(`Success: ${JSON.stringify(Ce,null,2)}`)}catch(Ee){V(`Error: ${Ee.message}`)}},"handleCallTool"),X=ze(async()=>{try{V("Sending follow-up message..."),await T(P),V("Follow-up message sent successfully")}catch(Ee){V(`Error: ${Ee.message}`)}},"handleSendFollowUpMessage"),se=ze(()=>{try{k(U),V(`Opened external link: ${U}`)}catch(Ee){V(`Error: ${Ee.message}`)}},"handleOpenExternal"),he=ze(async Ee=>{try{V(`Requesting display mode: ${Ee}...`);const Ce=await R(Ee);V(`Display mode granted: ${Ce.mode}`)}catch(Ce){V(`Error: ${Ce.message}`)}},"handleRequestDisplayMode"),Te=ze(async()=>{try{const Ee=m?{...m,debugTimestamp:new Date().toISOString()}:{debugTimestamp:new Date().toISOString()};V("Setting state..."),await A(Ee),V(`State updated: ${JSON.stringify(Ee,null,2)}`)}catch(Ee){V(`Error: ${Ee.message}`)}},"handleSetState"),Be=ze(async()=>{try{await R("fullscreen")}catch(Ee){console.error("Failed to go fullscreen:",Ee)}},"handleFullscreen"),$e=ze(async()=>{try{await R("pip")}catch(Ee){console.error("Failed to go pip:",Ee)}},"handlePip"),Ge=ze(()=>{const Ee=["absolute","px-2","py-1","bg-black/90","text-white","rounded","text-xs","whitespace-nowrap","pointer-events-none","transition-opacity","duration-200","ease-in-out"];switch(n){case"top-right":return[...Ee,"top-full","right-0","mt-2"];case"top-left":return[...Ee,"top-full","left-0","mt-2"];case"top-center":return[...Ee,"top-full","left-1/2","-translate-x-1/2","mt-2"];case"bottom-right":return[...Ee,"bottom-full","right-0","mb-2"];case"bottom-left":return[...Ee,"bottom-full","left-0","mb-2"];case"bottom-center":return[...Ee,"bottom-full","left-1/2","-translate-x-1/2","mb-2"];case"center-left":return[...Ee,"left-full","top-1/2","-translate-y-1/2","ml-2"];case"center-right":return[...Ee,"right-full","top-1/2","-translate-y-1/2","mr-2"];default:return[...Ee,"top-full","right-0","mt-2"]}},"getTooltipClasses"),dt=ze(({onClick:Ee,label:Ce,children:He})=>{const[st,Je]=y.useState(!1),it=Ge();return le.createElement("button",{className:`p-2 ${re?"bg-white/10 hover:bg-white/20":"bg-black/70 hover:bg-black/90"} text-white border-none rounded-lg cursor-pointer flex items-center justify-center w-8 h-8 transition-colors duration-200 backdrop-blur-md ${re?"shadow-[0_2px_8px_rgba(0,0,0,0.3)]":"shadow-[0_2px_8px_rgba(0,0,0,0.2)]"} relative`,onMouseEnter:()=>Je(!0),onMouseLeave:()=>Je(!1),onClick:Ee,"aria-label":Ce},le.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"block"},He),a&&le.createElement("span",{className:`${it.join(" ")} ${st?"opacity-100":"opacity-0"}`},Ce))},"IconButton"),Ve=ze(Ee=>{if(Ee===null)return"null";if(Ee===void 0)return"undefined";if(typeof Ee=="object")try{return JSON.stringify(Ee,null,2)}catch{return String(Ee)}return String(Ee)},"formatValue"),ct=ze(Ee=>Ee?`${Ee.device?.type||"unknown"}`:"N/A","formatUserAgent"),rt=ze(Ee=>{if(!Ee?.insets)return"N/A";const{top:Ce,bottom:He,left:st,right:Je}=Ee.insets;return`T:${Ce} B:${He} L:${st} R:${Je}`},"formatSafeArea");return le.createElement(le.Fragment,null,le.createElement("div",{ref:j,className:`${t} relative h-fit`,onMouseEnter:()=>!r&&O(!0),onMouseLeave:()=>!r&&O(!1)},le.createElement("div",{className:pe().join(" "),style:me()},!W&&le.createElement(le.Fragment,null,!$&&!G&&le.createElement(le.Fragment,null,(i===!0||i==="fullscreen")&&le.createElement(dt,{onClick:Be,label:"Fullscreen"},le.createElement("path",{d:"M15 3h6v6"}),le.createElement("path",{d:"m21 3-7 7"}),le.createElement("path",{d:"m3 21 7-7"}),le.createElement("path",{d:"M9 21H3v-6"})),(i===!0||i==="pip")&&le.createElement(dt,{onClick:$e,label:"Picture in Picture"},le.createElement("path",{d:"M21 9V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h4"}),le.createElement("rect",{width:"10",height:"7",x:"12",y:"13",rx:"2"}))),o&&le.createElement(dt,{onClick:ne,label:"Debug Info"},le.createElement("path",{d:"M12 20v-9"}),le.createElement("path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z"}),le.createElement("path",{d:"M14.12 3.88 16 2"}),le.createElement("path",{d:"M21 21a4 4 0 0 0-3.81-4"}),le.createElement("path",{d:"M21 5a4 4 0 0 1-3.55 3.97"}),le.createElement("path",{d:"M22 13h-4"}),le.createElement("path",{d:"M3 21a4 4 0 0 1 3.81-4"}),le.createElement("path",{d:"M3 5a4 4 0 0 0 3.55 3.97"}),le.createElement("path",{d:"M6 13H2"}),le.createElement("path",{d:"m8 2 1.88 1.88"}),le.createElement("path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13"})))),e),M&&o&&le.createElement("div",{ref:B,className:"fixed inset-0 bg-black text-white font-mono text-xs z-[10000] overflow-auto p-4",onClick:Ee=>{Ee.target===B.current&&L(!1)}},le.createElement("button",{onClick:()=>L(!1),className:"absolute top-4 right-4 bg-white/10 text-white border-none rounded w-8 h-8 cursor-pointer flex items-center justify-center text-lg leading-none","aria-label":"Close"},"×"),le.createElement("div",{className:"max-w-[1200px] mx-auto pt-10"},le.createElement("h1",{className:"text-lg font-bold mb-4 border-b border-gray-700 pb-2"},"Debug Info"),le.createElement("table",{className:"w-full border-collapse border-spacing-0"},le.createElement("tbody",null,le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Props"),le.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},Ve(l))),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Output"),le.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},Ve(u))),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Metadata"),le.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},Ve(f))),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"State"),le.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},Ve(m))),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Theme"),le.createElement("td",{className:"p-2"},h)),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Display Mode"),le.createElement("td",{className:"p-2"},g)),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Locale"),le.createElement("td",{className:"p-2"},w)),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Max Height"),le.createElement("td",{className:"p-2"},E,"px")),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"User Agent"),le.createElement("td",{className:"p-2"},ct(x))),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Safe Area"),le.createElement("td",{className:"p-2"},rt(b))),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"API Available"),le.createElement("td",{className:"p-2"},S?"Yes":"No")),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"window.openai Keys"),le.createElement("td",{className:"p-2"},K.length>0?K.join(", "):"N/A")))),le.createElement("h2",{className:"text-base font-bold mt-8 mb-4 border-b border-gray-700 pb-2"},"Actions"),le.createElement("div",{className:"flex flex-col gap-3"},le.createElement("div",{className:"flex gap-2 items-center"},le.createElement("input",{type:"text",value:Y,onChange:Ee=>F(Ee.target.value),placeholder:"Tool name",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs w-[150px]"}),le.createElement("input",{type:"text",value:ae,onChange:Ee=>ee(Ee.target.value),placeholder:'{"key": "value"}',className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),le.createElement("button",{onClick:J,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Call Tool")),le.createElement("div",{className:"flex gap-2 items-center"},le.createElement("input",{type:"text",value:P,onChange:Ee=>H(Ee.target.value),placeholder:"Follow-up message",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),le.createElement("button",{onClick:X,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Send Follow-Up")),le.createElement("div",{className:"flex gap-2 items-center"},le.createElement("input",{type:"text",value:U,onChange:Ee=>D(Ee.target.value),placeholder:"External URL",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),le.createElement("button",{onClick:se,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Open Link")),le.createElement("div",{className:"flex gap-2 items-center"},le.createElement("span",{className:"w-[150px] text-xs"},"Display Mode:"),le.createElement("button",{onClick:()=>he("inline"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"Inline"),le.createElement("button",{onClick:()=>he("pip"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"PiP"),le.createElement("button",{onClick:()=>he("fullscreen"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"Fullscreen")),le.createElement("div",{className:"flex gap-2 items-center"},le.createElement("button",{onClick:Te,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Set State (Add Timestamp)")),te&&le.createElement("div",{className:"mt-2 p-2 bg-[#1a1a1a] border border-gray-700 rounded whitespace-pre-wrap break-all text-[11px] max-h-[200px] overflow-auto"},le.createElement("div",{className:"font-bold mb-1 text-gray-400"},"Result:"),te,le.createElement("button",{onClick:()=>V(""),className:"mt-2 py-1 px-2 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-[11px]"},"Clear"))))))}ze(_B,"WidgetControls");function TB(){if(typeof window>"u")return"/";const t=window.location.pathname.match(/^(\/inspector\/api\/dev-widget\/[^/]+)/);return t?t[1]:"/"}ze(TB,"getBasename");var qre=150,Xre=5;function Jre({children:e,debugger:t=!1,viewControls:n=!1,autoSize:r=!1}){const a=TB(),o=y.useRef(null),i=y.useRef(0),l=y.useRef(null),u=y.useRef(!1),[f,m]=y.useState(null),[h,g]=y.useState(null),[b,E]=y.useState(!0);y.useEffect(()=>{let _=!0;return(async()=>{try{const T=await Ua(()=>import("./index-Em9frkKx.js"),[]);_&&(m(()=>T.BrowserRouter),E(!1))}catch{_&&(g(new Error(`❌ react-router not installed!
35
+ `&&r++}}return[t,n]}class Ire extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let a;super({start(o){a=bB({onEvent:i=>{o.enqueue(i)},onError(i){t==="terminate"?o.error(i):typeof t=="function"&&t(i)},onRetry:n,onComment:r})},transform(o){a.feed(o)}})}}const Ore={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Vi extends Error{constructor(t,n){super(`Streamable HTTP error: ${n}`),this.code=t}}class Dre{constructor(t,n){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=n?.requestInit,this._authProvider=n?.authProvider,this._fetch=n?.fetch,this._fetchWithInit=rB(n?.fetch,n?.requestInit),this._sessionId=n?.sessionId,this._reconnectionOptions=n?.reconnectionOptions??Ore}async _authThenStart(){if(!this._authProvider)throw new yo("No auth provider");let t;try{t=await Ks(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw this.onerror?.(n),n}if(t!=="AUTHORIZED")throw new yo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const t={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(t.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const n=Dy(this._requestInit?.headers);return new Headers({...t,...n})}async _startOrAuthSse(t){const{resumptionToken:n}=t;try{const r=await this._commonHeaders();r.set("Accept","text/event-stream"),n&&r.set("last-event-id",n);const a=await(this._fetch??fetch)(this._url,{method:"GET",headers:r,signal:this._abortController?.signal});if(!a.ok){if(await a.body?.cancel(),a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new Vi(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,t,!0)}catch(r){throw this.onerror?.(r),r}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const n=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,a=this._reconnectionOptions.maxReconnectionDelay;return Math.min(n*Math.pow(r,t),a)}_scheduleReconnection(t,n=0){const r=this._reconnectionOptions.maxRetries;if(n>=r){this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`));return}const a=this._getNextReconnectionDelay(n);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(t,n+1)})},a)}_handleSseStream(t,n,r){if(!t)return;const{onresumptiontoken:a,replayMessageId:o}=n;let i,l=!1,u=!1;(async()=>{try{const m=t.pipeThrough(new TextDecoderStream).pipeThrough(new Ire({onRetry:b=>{this._serverRetryMs=b}})).getReader();for(;;){const{value:b,done:E}=await m.read();if(E)break;if(b.id&&(i=b.id,l=!0,a?.(b.id)),!!b.data&&(!b.event||b.event==="message"))try{const x=qb.parse(JSON.parse(b.data));Sp(x)&&(u=!0,o!==void 0&&(x.id=o)),this.onmessage?.(x)}catch(x){this.onerror?.(x)}}(r||l)&&!u&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:o},0)}catch(m){if(this.onerror?.(new Error(`SSE stream disconnected: ${m}`)),(r||l)&&!u&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:o},0)}catch(b){this.onerror?.(new Error(`Failed to reconnect: ${b instanceof Error?b.message:String(b)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new yo("No auth provider");if(await Ks(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new yo("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,n){try{const{resumptionToken:r,onresumptiontoken:a}=n||{};if(r){this._startOrAuthSse({resumptionToken:r,replayMessageId:IS(t)?t.id:void 0}).catch(g=>this.onerror?.(g));return}const o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");const i={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(t),signal:this._abortController?.signal},l=await(this._fetch??fetch)(this._url,i),u=l.headers.get("mcp-session-id");if(u&&(this._sessionId=u),!l.ok){const g=await l.text().catch(()=>null);if(l.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Vi(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:b,scope:E}=nm(l);if(this._resourceMetadataUrl=b,this._scope=E,await Ks(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new yo;return this._hasCompletedAuthFlow=!0,this.send(t)}if(l.status===403&&this._authProvider){const{resourceMetadataUrl:b,scope:E,error:x}=nm(l);if(x==="insufficient_scope"){const w=l.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===w)throw new Vi(403,"Server returned 403 after trying upscoping");if(E&&(this._scope=E),b&&(this._resourceMetadataUrl=b),this._lastUpscopingHeader=w??void 0,await Ks(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new yo;return this.send(t)}}throw new Vi(l.status,`Error POSTing to endpoint: ${g}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,l.status===202){await l.body?.cancel(),xee(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(g=>this.onerror?.(g));return}const m=(Array.isArray(t)?t:[t]).filter(g=>"method"in g&&"id"in g&&g.id!==void 0).length>0,h=l.headers.get("content-type");if(m)if(h?.includes("text/event-stream"))this._handleSseStream(l.body,{onresumptiontoken:a},!1);else if(h?.includes("application/json")){const g=await l.json(),b=Array.isArray(g)?g.map(E=>qb.parse(E)):[qb.parse(g)];for(const E of b)this.onmessage?.(E)}else throw await l.body?.cancel(),new Vi(-1,`Unexpected content type: ${h}`);else await l.body?.cancel()}catch(r){throw this.onerror?.(r),r}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const t=await this._commonHeaders(),n={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._url,n);if(await r.body?.cancel(),!r.ok&&r.status!==405)throw new Vi(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,n){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:n?.onresumptiontoken})}}class S$ extends Event{constructor(t,n){var r,a;super(t),this.code=(r=n?.code)!=null?r:void 0,this.message=(a=n?.message)!=null?a:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,r){return r(_$(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(_$(this),n)}}function Lre(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function VS(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(VS).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${VS(e.cause)}`:e.message:`${e}`}function _$(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var yB=e=>{throw TypeError(e)},wN=(e,t,n)=>t.has(e)||yB("Cannot "+n),un=(e,t,n)=>(wN(e,t,"read from private field"),n?n.call(e):t.get(e)),Lr=(e,t,n)=>t.has(e)?yB("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),or=(e,t,n,r)=>(wN(e,t,"write to private field"),t.set(e,n),n),Vs=(e,t,n)=>(wN(e,t,"access private method"),n),$a,Zl,wu,Jb,$y,jp,Ou,Pp,Wi,xu,Yu,Eu,_p,jo,GS,WS,KS,T$,YS,ZS,Tp,qS,XS;class Qb extends EventTarget{constructor(t,n){var r,a;super(),Lr(this,jo),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Lr(this,$a),Lr(this,Zl),Lr(this,wu),Lr(this,Jb),Lr(this,$y),Lr(this,jp),Lr(this,Ou),Lr(this,Pp,null),Lr(this,Wi),Lr(this,xu),Lr(this,Yu,null),Lr(this,Eu,null),Lr(this,_p,null),Lr(this,WS,async o=>{var i;un(this,xu).reset();const{body:l,redirected:u,status:f,headers:m}=o;if(f===204){Vs(this,jo,Tp).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?or(this,wu,new URL(o.url)):or(this,wu,void 0),f!==200){Vs(this,jo,Tp).call(this,`Non-200 status code (${f})`,f);return}if(!(m.get("content-type")||"").startsWith("text/event-stream")){Vs(this,jo,Tp).call(this,'Invalid content type, expected "text/event-stream"',f);return}if(un(this,$a)===this.CLOSED)return;or(this,$a,this.OPEN);const h=new Event("open");if((i=un(this,_p))==null||i.call(this,h),this.dispatchEvent(h),typeof l!="object"||!l||!("getReader"in l)){Vs(this,jo,Tp).call(this,"Invalid response body, expected a web ReadableStream",f),this.close();return}const g=new TextDecoder,b=l.getReader();let E=!0;do{const{done:x,value:w}=await b.read();w&&un(this,xu).feed(g.decode(w,{stream:!x})),x&&(E=!1,un(this,xu).reset(),Vs(this,jo,qS).call(this))}while(E)}),Lr(this,KS,o=>{or(this,Wi,void 0),!(o.name==="AbortError"||o.type==="aborted")&&Vs(this,jo,qS).call(this,VS(o))}),Lr(this,YS,o=>{typeof o.id=="string"&&or(this,Pp,o.id);const i=new MessageEvent(o.event||"message",{data:o.data,origin:un(this,wu)?un(this,wu).origin:un(this,Zl).origin,lastEventId:o.id||""});un(this,Eu)&&(!o.event||o.event==="message")&&un(this,Eu).call(this,i),this.dispatchEvent(i)}),Lr(this,ZS,o=>{or(this,jp,o)}),Lr(this,XS,()=>{or(this,Ou,void 0),un(this,$a)===this.CONNECTING&&Vs(this,jo,GS).call(this)});try{if(t instanceof URL)or(this,Zl,t);else if(typeof t=="string")or(this,Zl,new URL(t,Mre()));else throw new Error("Invalid URL")}catch{throw Lre("An invalid or illegal string was specified")}or(this,xu,bB({onEvent:un(this,YS),onRetry:un(this,ZS)})),or(this,$a,this.CONNECTING),or(this,jp,3e3),or(this,$y,(r=n?.fetch)!=null?r:globalThis.fetch),or(this,Jb,(a=n?.withCredentials)!=null?a:!1),Vs(this,jo,GS).call(this)}get readyState(){return un(this,$a)}get url(){return un(this,Zl).href}get withCredentials(){return un(this,Jb)}get onerror(){return un(this,Yu)}set onerror(t){or(this,Yu,t)}get onmessage(){return un(this,Eu)}set onmessage(t){or(this,Eu,t)}get onopen(){return un(this,_p)}set onopen(t){or(this,_p,t)}addEventListener(t,n,r){const a=n;super.addEventListener(t,a,r)}removeEventListener(t,n,r){const a=n;super.removeEventListener(t,a,r)}close(){un(this,Ou)&&clearTimeout(un(this,Ou)),un(this,$a)!==this.CLOSED&&(un(this,Wi)&&un(this,Wi).abort(),or(this,$a,this.CLOSED),or(this,Wi,void 0))}}$a=new WeakMap,Zl=new WeakMap,wu=new WeakMap,Jb=new WeakMap,$y=new WeakMap,jp=new WeakMap,Ou=new WeakMap,Pp=new WeakMap,Wi=new WeakMap,xu=new WeakMap,Yu=new WeakMap,Eu=new WeakMap,_p=new WeakMap,jo=new WeakSet,GS=function(){or(this,$a,this.CONNECTING),or(this,Wi,new AbortController),un(this,$y)(un(this,Zl),Vs(this,jo,T$).call(this)).then(un(this,WS)).catch(un(this,KS))},WS=new WeakMap,KS=new WeakMap,T$=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...un(this,Pp)?{"Last-Event-ID":un(this,Pp)}:void 0},cache:"no-store",signal:(e=un(this,Wi))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},YS=new WeakMap,ZS=new WeakMap,Tp=function(e,t){var n;un(this,$a)!==this.CLOSED&&or(this,$a,this.CLOSED);const r=new S$("error",{code:t,message:e});(n=un(this,Yu))==null||n.call(this,r),this.dispatchEvent(r)},qS=function(e,t){var n;if(un(this,$a)===this.CLOSED)return;or(this,$a,this.CONNECTING);const r=new S$("error",{code:t,message:e});(n=un(this,Yu))==null||n.call(this,r),this.dispatchEvent(r),or(this,Ou,setTimeout(un(this,XS),un(this,jp)))},XS=new WeakMap,Qb.CONNECTING=0,Qb.OPEN=1,Qb.CLOSED=2;function Mre(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}class jre extends Error{constructor(t,n,r){super(`SSE error: ${n}`),this.code=t,this.event=r}}class Pre{constructor(t,n){this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=n?.eventSourceInit,this._requestInit=n?.requestInit,this._authProvider=n?.authProvider,this._fetch=n?.fetch,this._fetchWithInit=rB(n?.fetch,n?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new yo("No auth provider");let t;try{t=await Ks(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(n){throw this.onerror?.(n),n}if(t!=="AUTHORIZED")throw new yo;return await this._startOrAuth()}async _commonHeaders(){const t={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(t.Authorization=`Bearer ${r.access_token}`)}this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const n=Dy(this._requestInit?.headers);return new Headers({...t,...n})}_startOrAuth(){const t=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((n,r)=>{this._eventSource=new Qb(this._url.href,{...this._eventSourceInit,fetch:async(a,o)=>{const i=await this._commonHeaders();i.set("Accept","text/event-stream");const l=await t(a,{...o,headers:i});if(l.status===401&&l.headers.has("www-authenticate")){const{resourceMetadataUrl:u,scope:f}=nm(l);this._resourceMetadataUrl=u,this._scope=f}return l}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{if(a.code===401&&this._authProvider){this._authThenStart().then(n,r);return}const o=new jre(a.code,a.message,a);r(o),this.onerror?.(o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{const o=a;try{if(this._endpoint=new URL(o.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(i){r(i),this.onerror?.(i),this.close();return}n()}),this._eventSource.onmessage=a=>{const o=a;let i;try{i=qb.parse(JSON.parse(o.data))}catch(l){this.onerror?.(l);return}this.onmessage?.(i)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(t){if(!this._authProvider)throw new yo("No auth provider");if(await Ks(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new yo("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(t){if(!this._endpoint)throw new Error("Not connected");try{const n=await this._commonHeaders();n.set("content-type","application/json");const r={...this._requestInit,method:"POST",headers:n,body:JSON.stringify(t),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._endpoint,r);if(!a.ok){const o=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){const{resourceMetadataUrl:i,scope:l}=nm(a);if(this._resourceMetadataUrl=i,this._scope=l,await Ks(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new yo;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${a.status}): ${o}`)}await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}setProtocolVersion(t){this._protocolVersion=t}}var wd,$re=(wd=class{connector;autoConnect;constructor(t,n=!0){this.connector=t,this.autoConnect=n}async connect(){await this.connector.connect()}async disconnect(){await this.connector.disconnect()}async initialize(){!this.isConnected&&this.autoConnect&&await this.connect(),await this.connector.initialize()}get isConnected(){return this.connector&&this.connector.isClientConnected}on(t,n){t==="notification"&&this.connector.onNotification(n)}async setRoots(t){return this.connector.setRoots(t)}getRoots(){return this.connector.getRoots()}get tools(){return this.connector.tools}async listTools(t){return this.connector.listTools(t)}get serverCapabilities(){return this.connector.serverCapabilities}get serverInfo(){return this.connector.serverInfo}async callTool(t,n={},r){return this.connector.callTool(t,n,r)}async listResources(t,n){return this.connector.listResources(t,n)}async listAllResources(t){return this.connector.listAllResources(t)}async listResourceTemplates(t){return this.connector.listResourceTemplates(t)}async readResource(t,n){return this.connector.readResource(t,n)}async subscribeToResource(t,n){return this.connector.subscribeToResource(t,n)}async unsubscribeFromResource(t,n){return this.connector.unsubscribeFromResource(t,n)}async listPrompts(){return this.connector.listPrompts()}async getPrompt(t,n){return this.connector.getPrompt(t,n)}async request(t,n=null,r){return this.connector.request(t,n,r)}},ze(wd,"MCPSession"),wd),xd,Ure=(xd=class{config={};sessions={};activeSessions=[];constructor(t){t&&(this.config=t)}static fromDict(t){throw new Error("fromDict must be implemented by concrete class")}addServer(t,n){this.config.mcpServers=this.config.mcpServers||{},this.config.mcpServers[t]=n,rs.getInstance().trackClientAddServer(t,n)}removeServer(t){this.config.mcpServers?.[t]&&(delete this.config.mcpServers[t],this.activeSessions=this.activeSessions.filter(n=>n!==t),rs.getInstance().trackClientRemoveServer(t))}getServerNames(){return Object.keys(this.config.mcpServers??{})}getServerConfig(t){return this.config.mcpServers?.[t]}getConfig(){return this.config??{}}async createSession(t,n=!0){const r=this.config.mcpServers??{};if(Object.keys(r).length===0&&Fe.warn("No MCP servers defined in config"),!r[t])throw new Error(`Server '${t}' not found in config`);const a=this.createConnectorFromConfig(r[t]),o=new $re(a);return n&&await o.initialize(),this.sessions[t]=o,this.activeSessions.includes(t)||this.activeSessions.push(t),o}async createAllSessions(t=!0){const n=this.config.mcpServers??{};Object.keys(n).length===0&&Fe.warn("No MCP servers defined in config");for(const r of Object.keys(n))await this.createSession(r,t);return this.sessions}getSession(t){const n=this.sessions[t];return n||null}requireSession(t){const n=this.sessions[t];if(!n)throw new Error(`Session '${t}' not found. Available sessions: ${this.activeSessions.join(", ")||"none"}`);return n}getAllActiveSessions(){return Object.fromEntries(this.activeSessions.map(t=>[t,this.sessions[t]]))}async closeSession(t){const n=this.sessions[t];if(!n){Fe.warn(`No session exists for server ${t}, nothing to close`);return}try{Fe.debug(`Closing session for server ${t}`),await n.disconnect()}catch(r){Fe.error(`Error closing session for server '${t}': ${r}`)}finally{delete this.sessions[t],this.activeSessions=this.activeSessions.filter(r=>r!==t)}}async closeAllSessions(){const t=Object.keys(this.sessions),n=[];for(const r of t)try{Fe.debug(`Closing session for server ${r}`),await this.closeSession(r)}catch(a){const o=`Failed to close session for server '${r}': ${a}`;Fe.error(o),n.push(o)}n.length?Fe.error(`Encountered ${n.length} errors while closing sessions`):Fe.debug("All sessions closed successfully")}},ze(xd,"BaseMCPClient"),xd),Ed,zre=(Ed=class{_readyPromise;_readyResolver;_donePromise;_doneResolver;_exception=null;_connection=null;_task=null;_abortController=null;constructor(){this.reset()}async start(){if(this.reset(),Fe.debug(`Starting ${this.constructor.name}`),this._task=this.connectionTask(),await this._readyPromise,this._exception)throw this._exception;if(this._connection===null)throw new Error("Connection was not established");return this._connection}async stop(){if(this._task&&this._abortController){Fe.debug(`Cancelling ${this.constructor.name} task`),this._abortController.abort();try{await this._task}catch(t){t instanceof Error&&t.name==="AbortError"?Fe.debug(`${this.constructor.name} task aborted successfully`):Fe.warn(`Error stopping ${this.constructor.name} task: ${t}`)}}await this._donePromise,Fe.debug(`${this.constructor.name} task completed`)}reset(){this._readyPromise=new Promise(t=>this._readyResolver=t),this._donePromise=new Promise(t=>this._doneResolver=t),this._exception=null,this._connection=null,this._task=null,this._abortController=new AbortController}async connectionTask(){Fe.debug(`Running ${this.constructor.name} task`);try{this._connection=await this.establishConnection(),Fe.debug(`${this.constructor.name} connected successfully`),this._readyResolver(),await this.waitForAbort()}catch(t){this._exception=t,Fe.error(`Error in ${this.constructor.name} task: ${t}`),this._readyResolver()}finally{if(this._connection!==null){try{await this.closeConnection(this._connection)}catch(t){Fe.warn(`Error closing connection in ${this.constructor.name}: ${t}`)}this._connection=null}this._doneResolver()}}async waitForAbort(){return new Promise((t,n)=>{if(!this._abortController)return;const r=this._abortController.signal;if(r.aborted){t();return}const a=ze(()=>{r.removeEventListener("abort",a),t()},"onAbort");r.addEventListener("abort",a)})}},ze(Ed,"ConnectionManager"),Ed),Sd,Fre=(Sd=class extends zre{url;opts;_transport=null;reinitializing=!1;constructor(t,n){super(),this.url=typeof t=="string"?new URL(t):t,this.opts=n}async establishConnection(){const t=new Pre(this.url,this.opts),n=t.send.bind(t);return t.send=async r=>{const a=ze(async o=>{if(Array.isArray(o))for(const i of o)await n(i);else await n(o)},"sendMessage");try{await a(r)}catch(o){if(o?.code===404&&t.sessionId&&!this.reinitializing){Fe.warn("[SSE] Session not found (404), re-initializing per MCP spec..."),this.reinitializing=!0;try{t.sessionId=void 0,await this.reinitialize(t),Fe.info("[SSE] Re-initialization successful, retrying request"),await a(r)}finally{this.reinitializing=!1}}else throw o}},this._transport=t,Fe.debug(`${this.constructor.name} connected successfully`),t}async reinitialize(t){Fe.debug("[SSE] Re-initialization triggered")}async closeConnection(t){if(this._transport)try{await this._transport.close()}catch(n){Fe.warn(`Error closing SSE transport: ${n}`)}finally{this._transport=null}}},ze(Sd,"SseConnectionManager"),Sd),_d,Bre=(_d=class extends Pte{baseUrl;headers;timeout;sseReadTimeout;clientInfo;preferSse;disableSseFallback;gatewayUrl;serverId;transportType=null;streamableTransport=null;constructor(t,n={}){super(n);const r=t.replace(/\/$/,"");this.gatewayUrl=n.gatewayUrl,this.serverId=n.serverId,this.gatewayUrl?(this.baseUrl=this.gatewayUrl.replace(/\/$/,""),this.headers={...n.headers??{}},this.headers["X-Target-URL"]=r,this.serverId&&(this.headers["X-Server-Id"]=this.serverId)):(this.baseUrl=r,this.headers={...n.headers??{}}),n.authToken&&(this.headers.Authorization=`Bearer ${n.authToken}`),this.timeout=n.timeout??1e4,this.sseReadTimeout=n.sseReadTimeout??3e5,this.clientInfo=n.clientInfo??{name:"http-connector",version:"1.0.0"},this.preferSse=n.preferSse??!1,this.disableSseFallback=n.disableSseFallback??!1}async connect(){if(this.connected){Fe.debug("Already connected to MCP implementation");return}const t=this.baseUrl;if(this.preferSse){Fe.debug(`Connecting to MCP implementation via HTTP/SSE: ${t}`),await this.connectWithSse(t);return}Fe.debug(`Connecting to MCP implementation via HTTP: ${t}`);try{Fe.info("🔄 Attempting streamable HTTP transport..."),await this.connectWithStreamableHttp(t),Fe.info("✅ Successfully connected via streamable HTTP")}catch(n){console.log("error in http connector connect",n);let r="Unknown error",a=!1,o,i=null;if(n instanceof Vi?i=n:n instanceof Error&&n.cause instanceof Vi&&(i=n.cause),i)a=i.code===401,o=i.code,console.log("Captured HTTP status code:",o),i.code===400&&i.message.includes("Missing session ID")?(r="Server requires session ID (FastMCP compatibility) - using SSE transport",Fe.warn(`⚠️ ${r}`)):i.code===404||i.code===405?(r=`Server returned ${i.code} - server likely doesn't support streamable HTTP`,Fe.debug(r)):(r=`Server returned ${i.code}: ${i.message}`,Fe.debug(r));else if(n instanceof Error){const l=n.toString(),u=n.message||"";a=l.includes("401")||u.includes("Unauthorized"),l.includes("Missing session ID")||l.includes("Bad Request: Missing session ID")||u.includes("FastMCP session ID error")?(r="Server requires session ID (FastMCP compatibility) - using SSE transport",Fe.warn(`⚠️ ${r}`)):l.includes("405 Method Not Allowed")||l.includes("404 Not Found")?(r="Server doesn't support streamable HTTP (405/404)",Fe.debug(r)):(r=`Streamable HTTP failed: ${n.message}`,Fe.debug(r))}if(a){Fe.info("Authentication required - skipping SSE fallback"),await this.cleanupResources();const l=new Error("Authentication required");throw l.code=401,l}Fe.info("🔄 Falling back to SSE transport...");try{await this.connectWithSse(t)}catch(l){if(console.error("Failed to connect with both transports:"),console.error(` Streamable HTTP: ${r}`),console.error(` SSE: ${l}`),await this.cleanupResources(),l?.message?.includes("401")||l?.message?.includes("Unauthorized")){const m=new Error("Authentication required");throw m.code=401,m}const f=new Error(`Could not connect to server with any available transport. Streamable HTTP: ${r}`);throw o!==void 0&&(Object.defineProperty(f,"code",{value:o,writable:!1,enumerable:!0,configurable:!0}),Fe.debug(`Preserving HTTP status code ${o} in error for proxy fallback detection`)),f}}}async connectWithStreamableHttp(t){try{console.log("[HttpConnector] Connecting with Streamable HTTP:"),console.log(` Base URL: ${t}`),console.log(` Original URL: ${this.baseUrl}`),console.log(` Gateway URL: ${this.gatewayUrl||"none"}`),console.log(` Auth Provider URL: ${this.opts.authProvider?.serverUrl||"none"}`),console.log(` Headers: ${JSON.stringify(this.headers)}`);const n=new Dre(new URL(t),{authProvider:this.opts.authProvider,requestInit:{headers:this.headers},reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:2}});let r=n;if(this.opts.wrapTransport){const o=this.baseUrl;r=this.opts.wrapTransport(r,o)}const a={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};Fe.debug("Creating Client with capabilities:",JSON.stringify(a.capabilities,null,2)),this.client=new v$(this.clientInfo,a),this.setupRootsHandler(),Fe.debug("Roots handler registered before connect");try{await this.client.connect(r,{timeout:this.timeout});const o=n.sessionId;o?Fe.debug(`Session ID obtained: ${o}`):Fe.warn("Session ID not available after connect - this may cause issues with SSE stream")}catch(o){if(o instanceof Error){const i=o.message||o.toString();if(i.includes("Missing session ID")||i.includes("Bad Request: Missing session ID")||i.includes("Mcp-Session-Id header is required")){const l=new Error(`Session ID error: ${i}. The SDK should automatically extract session ID from initialize response.`);throw l.cause=o,l}}throw o}this.streamableTransport=n,this.connectionManager={stop:ze(async()=>{if(this.streamableTransport)try{await this.streamableTransport.terminateSession(),await this.streamableTransport.close()}catch(o){Fe.warn(`Error closing Streamable HTTP transport: ${o}`)}finally{this.streamableTransport=null}},"stop")},this.connected=!0,this.transportType="streamable-http",this.setupNotificationHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),Fe.debug(`Successfully connected to MCP implementation via streamable HTTP: ${t}`),this.trackConnectorInit({serverUrl:this.baseUrl,publicIdentifier:`${this.baseUrl} (streamable-http)`})}catch(n){throw await this.cleanupResources(),n}}async connectWithSse(t){try{this.connectionManager=new Fre(t,{authProvider:this.opts.authProvider,requestInit:{headers:this.headers}});let n=await this.connectionManager.start();if(this.opts.wrapTransport){const a=this.baseUrl;n=this.opts.wrapTransport(n,a)}const r={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};Fe.debug("Creating Client with capabilities (SSE):",JSON.stringify(r.capabilities,null,2)),this.client=new v$(this.clientInfo,r),this.setupRootsHandler(),Fe.debug("Roots handler registered before connect (SSE)"),await this.client.connect(n),this.connected=!0,this.transportType="sse",this.setupNotificationHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),Fe.debug(`Successfully connected to MCP implementation via HTTP/SSE: ${t}`),this.trackConnectorInit({serverUrl:this.baseUrl,publicIdentifier:`${this.baseUrl} (sse)`})}catch(n){throw await this.cleanupResources(),n}}get publicIdentifier(){return{type:"http",url:this.baseUrl,transport:this.transportType||"unknown"}}getTransportType(){return this.transportType}},ze(_d,"HttpConnector"),_d),lc,Hre=(lc=class extends Ure{static getPackageVersion(){return Sv()}constructor(t){super(t),this._trackClientInit()}_trackClientInit(){const t=Object.keys(this.config.mcpServers??{});rs.getInstance().trackMCPClientInit({codeMode:!1,sandbox:!1,allCallbacks:!1,verify:!1,servers:t,numServers:t.length,isBrowser:!0}).catch(n=>Fe.debug(`Failed to track BrowserMCPClient init: ${n}`))}static fromDict(t){return new lc(t)}createConnectorFromConfig(t){const{url:n,headers:r,authToken:a,authProvider:o,wrapTransport:i,clientOptions:l,onSampling:u,samplingCallback:f,elicitationCallback:m,disableSseFallback:h,preferSse:g,clientInfo:b,gatewayUrl:E,serverId:x}=t;if(!n)throw new Error("Server URL is required");const w=u??f,S={headers:r,authToken:a,authProvider:o,wrapTransport:i,clientOptions:l,onSampling:w,samplingCallback:w,elicitationCallback:m,disableSseFallback:h,preferSse:g,clientInfo:b,gatewayUrl:E,serverId:x};return l?console.log("[BrowserMCPClient] Passing clientOptions to connector:",JSON.stringify(l,null,2)):console.warn("[BrowserMCPClient] No clientOptions provided to connector!"),new Bre(n,S)}},ze(lc,"BrowserMCPClient"),lc);function Du(e){const t=ze(()=>{throw new Error(`Invalid url to pass to open(): ${e}`)},"abort");let n;try{n=new URL(e)}catch{t()}return n.protocol!=="https:"&&n.protocol!=="http:"&&t(),n.hostname!==encodeURIComponent(n.hostname)&&t(),n.username&&(n.username=encodeURIComponent(n.username)),n.password&&(n.password=encodeURIComponent(n.password)),n.pathname=n.pathname.slice(0,1)+encodeURIComponent(n.pathname.slice(1)).replace(/%2f/gi,"/"),n.search=n.search.slice(0,1)+Array.from(n.searchParams.entries()).map(vB).join("&"),n.hash=n.hash.slice(0,1)+encodeURIComponent(n.hash.slice(1)),n.href}ze(Du,"sanitizeUrl");function vB([e,t]){return`${encodeURIComponent(e)}${t.length>0?`=${encodeURIComponent(t)}`:""}`}ze(vB,"sanitizeParam");async function wB(e){return typeof e=="string"?e:e instanceof URLSearchParams||e instanceof FormData?Object.fromEntries(e.entries()):e instanceof Blob?await e.text():e}ze(wB,"serializeBody");var Td,ey=(Td=class{serverUrl;storageKeyPrefix;serverUrlHash;clientName;clientUri;logoUri;callbackUrl;preventAutoAuth;useRedirectFlow;oauthProxyUrl;connectionUrl;originalFetch;onPopupWindow;constructor(t,n={}){this.serverUrl=t,this.storageKeyPrefix=n.storageKeyPrefix||"mcp:auth",this.serverUrlHash=this.hashString(t),this.clientName=n.clientName||"mcp-use",this.clientUri=n.clientUri||(typeof window<"u"?window.location.origin:""),this.logoUri=n.logoUri||"https://mcp-use.com/logo.png",this.callbackUrl=Du(n.callbackUrl||(typeof window<"u"?new URL("/oauth/callback",window.location.origin).toString():"/oauth/callback")),this.preventAutoAuth=n.preventAutoAuth,this.useRedirectFlow=n.useRedirectFlow,this.oauthProxyUrl=n.oauthProxyUrl,this.connectionUrl=n.connectionUrl,this.onPopupWindow=n.onPopupWindow}installFetchInterceptor(){if(!this.oauthProxyUrl){console.warn("[BrowserOAuthProvider] No OAuth proxy URL configured, skipping fetch interceptor installation");return}if(!this.originalFetch)this.originalFetch=window.fetch;else{console.warn("[BrowserOAuthProvider] Fetch interceptor already installed");return}const t=this.oauthProxyUrl,n=this.connectionUrl,r=this.originalFetch;console.log(`[BrowserOAuthProvider] Installing fetch interceptor with proxy: ${t}`),window.fetch=ze(async function(o,i){const l=typeof o=="string"?o:o instanceof URL?o.toString():o.url;if(!(l.includes("/.well-known/")||l.match(/\/(register|token|authorize)$/)))return await r(o,i);try{const f=new URL(l),m=new URL(t);if(f.origin===m.origin&&(f.pathname.startsWith(m.pathname)||l.includes("/inspector/api/oauth")))return await r(o,i)}catch{}try{const f=l.includes("/.well-known/"),m=f?`${t}/metadata?url=${encodeURIComponent(l)}`:`${t}/proxy`;if(console.log(`[OAuth Proxy] Routing ${f?"metadata":"request"} through: ${m}`),f){const E={...i?.headers?Object.fromEntries(new Headers(i.headers)):{}};return n&&(E["X-Connection-URL"]=n),await r(m,{...i,method:"GET",headers:E})}const h=i?.body?await wB(i.body):void 0,b=await(await r(m,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:l,method:i?.method||"POST",headers:i?.headers?Object.fromEntries(new Headers(i.headers)):{},body:h})})).json();return new Response(JSON.stringify(b.body),{status:b.status,statusText:b.statusText,headers:new Headers(b.headers)})}catch(f){return console.error("[OAuth Proxy] Request failed, falling back to direct fetch:",f),await r(o,i)}},"interceptedFetch")}restoreFetch(){this.originalFetch&&(console.log("[BrowserOAuthProvider] Restoring original fetch"),window.fetch=this.originalFetch,this.originalFetch=void 0)}get redirectUrl(){return Du(this.callbackUrl)}get clientMetadata(){return{redirect_uris:[this.redirectUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:this.clientName,client_uri:this.clientUri,logo_uri:this.logoUri}}async clientInformation(){const t=this.getKey("client_info"),n=localStorage.getItem(t);if(n)try{return JSON.parse(n)}catch(r){console.warn(`[${this.storageKeyPrefix}] Failed to parse client information:`,r),localStorage.removeItem(t);return}}async saveClientInformation(t){const n=this.getKey("client_info");localStorage.setItem(n,JSON.stringify(t))}async tokens(){const t=this.getKey("tokens"),n=localStorage.getItem(t);if(n)try{return JSON.parse(n)}catch(r){console.warn(`[${this.storageKeyPrefix}] Failed to parse tokens:`,r),localStorage.removeItem(t);return}}async saveTokens(t){const n=this.getKey("tokens");localStorage.setItem(n,JSON.stringify(t)),localStorage.removeItem(this.getKey("code_verifier")),localStorage.removeItem(this.getKey("last_auth_url"))}async saveCodeVerifier(t){const n=this.getKey("code_verifier");localStorage.setItem(n,t)}async codeVerifier(){const t=this.getKey("code_verifier"),n=localStorage.getItem(t);if(!n)throw new Error(`[${this.storageKeyPrefix}] Code verifier not found in storage for key ${t}. Auth flow likely corrupted or timed out.`);return n}async prepareAuthorizationUrl(t){const n=globalThis.crypto.randomUUID(),r=`${this.storageKeyPrefix}:state_${n}`,a={serverUrlHash:this.serverUrlHash,expiry:Date.now()+1e3*60*10,providerOptions:{serverUrl:this.serverUrl,storageKeyPrefix:this.storageKeyPrefix,clientName:this.clientName,clientUri:this.clientUri,callbackUrl:this.callbackUrl},flowType:this.useRedirectFlow?"redirect":"popup",returnUrl:typeof window<"u"?window.location.href:void 0};console.log(`[OAuth] Storing state key: ${r}`),localStorage.setItem(r,JSON.stringify(a));const o=localStorage.getItem(r);console.log(`[OAuth] State stored successfully: ${!!o}`),t.searchParams.set("state",n);const i=t.toString(),l=Du(i);return localStorage.setItem(this.getKey("last_auth_url"),l),l}async redirectToAuthorization(t){const n=await this.prepareAuthorizationUrl(t);if(this.preventAutoAuth){console.info(`[${this.storageKeyPrefix}] Auto-auth prevented. Authorization URL stored for manual trigger.`);return}if(this.useRedirectFlow){console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL (full-page redirect).`),window.location.href=n;return}const r="width=600,height=700,resizable=yes,scrollbars=yes,status=yes";try{const a=window.open(n,`mcp_auth_${this.serverUrlHash}`,r);this.onPopupWindow&&this.onPopupWindow(n,r,a),!a||a.closed||typeof a.closed>"u"?console.warn(`[${this.storageKeyPrefix}] Popup likely blocked by browser. Manual navigation might be required using the stored URL.`):(a.focus(),console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`))}catch(a){console.error(`[${this.storageKeyPrefix}] Error opening popup window:`,a)}}getLastAttemptedAuthUrl(){const t=localStorage.getItem(this.getKey("last_auth_url"));return t?Du(t):null}clearStorage(){const t=`${this.storageKeyPrefix}_${this.serverUrlHash}_`,n=`${this.storageKeyPrefix}:state_`,r=[];let a=0;for(let i=0;i<localStorage.length;i++){const l=localStorage.key(i);if(l){if(l.startsWith(t))r.push(l);else if(l.startsWith(n))try{const u=localStorage.getItem(l);u&&JSON.parse(u).serverUrlHash===this.serverUrlHash&&r.push(l)}catch(u){console.warn(`[${this.storageKeyPrefix}] Error parsing state key ${l} during clearStorage:`,u)}}}return[...new Set(r)].forEach(i=>{localStorage.removeItem(i),a++}),a}hashString(t){let n=0;for(let r=0;r<t.length;r++){const a=t.charCodeAt(r);n=(n<<5)-n+a,n=n&n}return Math.abs(n).toString(16)}getKey(t){return`${this.storageKeyPrefix}_${this.serverUrlHash}_${t}`}},ze(Td,"BrowserOAuthClientProvider"),Td);async function xN(){const e=new URLSearchParams(window.location.search),t=e.get("code"),n=e.get("state"),r=e.get("error"),a=e.get("error_description"),o="[mcp-callback]";console.log(`${o} Handling callback...`,{code:t,state:n,error:r,errorDescription:a});let i=null,l=null,u=null;try{if(r)throw new Error(`OAuth error: ${r} - ${a||"No description provided."}`);if(!t)throw new Error("Authorization code not found in callback query parameters.");if(!n)throw new Error("State parameter not found or invalid in callback query parameters.");console.log(`[mcp-callback] Looking for state: ${n}`),console.log("[mcp-callback] All localStorage keys:",Object.keys(localStorage));const f=`mcp:auth:state_${n}`;if(localStorage.getItem(f))u=f,console.log(`[mcp-callback] Found state with default key: ${f}`);else{const x=`:state_${n}`;for(let w=0;w<localStorage.length;w++){const S=localStorage.key(w);if(S&&S.endsWith(x)){u=S,console.log(`[mcp-callback] Found state with dynamic key: ${S}`);break}}}if(!u){const x=Object.keys(localStorage).filter(w=>w.includes("state"));throw console.log("[mcp-callback] State keys in storage:",x),new Error(`Invalid or expired state parameter "${n}". No matching state found in storage.`)}const m=localStorage.getItem(u);if(!m)throw new Error(`Invalid or expired state parameter "${n}". No matching state found in storage.`);try{l=JSON.parse(m)}catch{throw new Error("Failed to parse stored OAuth state.")}if(!l.expiry||l.expiry<Date.now())throw localStorage.removeItem(u),new Error("OAuth state has expired. Please try initiating authentication again.");if(!l.providerOptions)throw new Error("Stored state is missing required provider options.");const{serverUrl:h,...g}=l.providerOptions;console.log(`${o} Re-instantiating provider for server: ${h}`),i=new ey(h,g),console.log(`${o} Calling SDK auth() to exchange code...`);const b=new URL(h).origin,E=await Ks(i,{serverUrl:b,authorizationCode:t});if(E==="AUTHORIZED")if(console.log(`${o} Authorization successful via SDK auth().`),l.flowType==="redirect"&&l.returnUrl)console.log(`${o} Redirect flow complete. Returning to: ${l.returnUrl}`),localStorage.removeItem(u),window.location.href=l.returnUrl;else if(window.opener&&!window.opener.closed)console.log(`${o} Popup flow complete. Notifying opener...`),window.opener.postMessage({type:"mcp_auth_callback",success:!0},window.location.origin),localStorage.removeItem(u),window.close();else if(l.returnUrl)console.log(`${o} Popup flow without opener. Returning to: ${l.returnUrl}`),localStorage.removeItem(u),window.location.href=l.returnUrl;else{console.warn(`${o} No opener window or return URL detected. Redirecting to root.`),localStorage.removeItem(u);const w=window.location.pathname.split("/").filter(Boolean),S=w.length>0&&w[w.length-1]==="callback"?"/"+w.slice(0,-2).join("/"):"/";window.location.href=S||"/"}else throw console.warn(`${o} SDK auth() returned unexpected status: ${E}`),new Error(`Unexpected result from authentication library: ${E}`)}catch(f){console.error(`${o} Error during OAuth callback handling:`,f);const m=f instanceof Error?f.message:String(f);window.opener&&!window.opener.closed&&window.opener.postMessage({type:"mcp_auth_callback",success:!1,error:m},window.location.origin);try{document.body.innerHTML="";const h=document.createElement("div");h.style.fontFamily="sans-serif",h.style.padding="20px";const g=document.createElement("h1");g.textContent="Authentication Error",h.appendChild(g);const b=document.createElement("p");b.style.color="red",b.style.backgroundColor="#ffebeb",b.style.border="1px solid red",b.style.padding="10px",b.style.borderRadius="4px",b.textContent=m,h.appendChild(b);const E=document.createElement("p");E.textContent="You can close this window or ";const x=document.createElement("a");if(x.href="#",x.textContent="click here to close",x.onclick=w=>(w.preventDefault(),window.close(),!1),E.appendChild(x),E.appendChild(document.createTextNode(".")),h.appendChild(E),f instanceof Error&&f.stack){const w=document.createElement("pre");w.style.fontSize="0.8em",w.style.color="#555",w.style.marginTop="20px",w.style.whiteSpace="pre-wrap",w.textContent=f.stack,h.appendChild(w)}document.body.appendChild(h)}catch(h){console.error(`${o} Could not display error in callback window:`,h)}u&&localStorage.removeItem(u),i&&(localStorage.removeItem(i.getKey("code_verifier")),localStorage.removeItem(i.getKey("last_auth_url")))}}ze(xN,"onMcpAuthorization");var bE={exports:{}},Bt={};var N$;function Vre(){if(N$)return Bt;N$=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),i=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),f=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),g=Symbol.iterator;function b(P){return P===null||typeof P!="object"?null:(P=g&&P[g]||P["@@iterator"],typeof P=="function"?P:null)}var E={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x=Object.assign,w={};function S(P,H,U){this.props=P,this.context=H,this.refs=w,this.updater=U||E}S.prototype.isReactComponent={},S.prototype.setState=function(P,H){if(typeof P!="object"&&typeof P!="function"&&P!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,P,H,"setState")},S.prototype.forceUpdate=function(P){this.updater.enqueueForceUpdate(this,P,"forceUpdate")};function _(){}_.prototype=S.prototype;function T(P,H,U){this.props=P,this.context=H,this.refs=w,this.updater=U||E}var k=T.prototype=new _;k.constructor=T,x(k,S.prototype),k.isPureReactComponent=!0;var R=Array.isArray;function A(){}var C={H:null,A:null,T:null,S:null},O=Object.prototype.hasOwnProperty;function M(P,H,U){var D=U.ref;return{$$typeof:e,type:P,key:H,ref:D!==void 0?D:null,props:U}}function L(P,H){return M(P.type,H,P.props)}function j(P){return typeof P=="object"&&P!==null&&P.$$typeof===e}function B(P){var H={"=":"=0",":":"=2"};return"$"+P.replace(/[=:]/g,function(U){return H[U]})}var K=/\/+/g;function Z(P,H){return typeof P=="object"&&P!==null&&P.key!=null?B(""+P.key):H.toString(36)}function te(P){switch(P.status){case"fulfilled":return P.value;case"rejected":throw P.reason;default:switch(typeof P.status=="string"?P.then(A,A):(P.status="pending",P.then(function(H){P.status==="pending"&&(P.status="fulfilled",P.value=H)},function(H){P.status==="pending"&&(P.status="rejected",P.reason=H)})),P.status){case"fulfilled":return P.value;case"rejected":throw P.reason}}throw P}function V(P,H,U,D,$){var G=typeof P;(G==="undefined"||G==="boolean")&&(P=null);var W=!1;if(P===null)W=!0;else switch(G){case"bigint":case"string":case"number":W=!0;break;case"object":switch(P.$$typeof){case e:case t:W=!0;break;case m:return W=P._init,V(W(P._payload),H,U,D,$)}}if(W)return $=$(P),W=D===""?"."+Z(P,0):D,R($)?(U="",W!=null&&(U=W.replace(K,"$&/")+"/"),V($,H,U,"",function(me){return me})):$!=null&&(j($)&&($=L($,U+($.key==null||P&&P.key===$.key?"":(""+$.key).replace(K,"$&/")+"/")+W)),H.push($)),1;W=0;var re=D===""?".":D+":";if(R(P))for(var pe=0;pe<P.length;pe++)D=P[pe],G=re+Z(D,pe),W+=V(D,H,U,G,$);else if(pe=b(P),typeof pe=="function")for(P=pe.call(P),pe=0;!(D=P.next()).done;)D=D.value,G=re+Z(D,pe++),W+=V(D,H,U,G,$);else if(G==="object"){if(typeof P.then=="function")return V(te(P),H,U,D,$);throw H=String(P),Error("Objects are not valid as a React child (found: "+(H==="[object Object]"?"object with keys {"+Object.keys(P).join(", ")+"}":H)+"). If you meant to render a collection of children, use an array instead.")}return W}function Y(P,H,U){if(P==null)return P;var D=[],$=0;return V(P,D,"","",function(G){return H.call(U,G,$++)}),D}function F(P){if(P._status===-1){var H=P._result;H=H(),H.then(function(U){(P._status===0||P._status===-1)&&(P._status=1,P._result=U)},function(U){(P._status===0||P._status===-1)&&(P._status=2,P._result=U)}),P._status===-1&&(P._status=0,P._result=H)}if(P._status===1)return P._result.default;throw P._result}var ae=typeof reportError=="function"?reportError:function(P){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var H=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof P=="object"&&P!==null&&typeof P.message=="string"?String(P.message):String(P),error:P});if(!window.dispatchEvent(H))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",P);return}console.error(P)},ee={map:Y,forEach:function(P,H,U){Y(P,function(){H.apply(this,arguments)},U)},count:function(P){var H=0;return Y(P,function(){H++}),H},toArray:function(P){return Y(P,function(H){return H})||[]},only:function(P){if(!j(P))throw Error("React.Children.only expected to receive a single React element child.");return P}};return Bt.Activity=h,Bt.Children=ee,Bt.Component=S,Bt.Fragment=n,Bt.Profiler=a,Bt.PureComponent=T,Bt.StrictMode=r,Bt.Suspense=u,Bt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=C,Bt.__COMPILER_RUNTIME={__proto__:null,c:function(P){return C.H.useMemoCache(P)}},Bt.cache=function(P){return function(){return P.apply(null,arguments)}},Bt.cacheSignal=function(){return null},Bt.cloneElement=function(P,H,U){if(P==null)throw Error("The argument must be a React element, but you passed "+P+".");var D=x({},P.props),$=P.key;if(H!=null)for(G in H.key!==void 0&&($=""+H.key),H)!O.call(H,G)||G==="key"||G==="__self"||G==="__source"||G==="ref"&&H.ref===void 0||(D[G]=H[G]);var G=arguments.length-2;if(G===1)D.children=U;else if(1<G){for(var W=Array(G),re=0;re<G;re++)W[re]=arguments[re+2];D.children=W}return M(P.type,$,D)},Bt.createContext=function(P){return P={$$typeof:i,_currentValue:P,_currentValue2:P,_threadCount:0,Provider:null,Consumer:null},P.Provider=P,P.Consumer={$$typeof:o,_context:P},P},Bt.createElement=function(P,H,U){var D,$={},G=null;if(H!=null)for(D in H.key!==void 0&&(G=""+H.key),H)O.call(H,D)&&D!=="key"&&D!=="__self"&&D!=="__source"&&($[D]=H[D]);var W=arguments.length-2;if(W===1)$.children=U;else if(1<W){for(var re=Array(W),pe=0;pe<W;pe++)re[pe]=arguments[pe+2];$.children=re}if(P&&P.defaultProps)for(D in W=P.defaultProps,W)$[D]===void 0&&($[D]=W[D]);return M(P,G,$)},Bt.createRef=function(){return{current:null}},Bt.forwardRef=function(P){return{$$typeof:l,render:P}},Bt.isValidElement=j,Bt.lazy=function(P){return{$$typeof:m,_payload:{_status:-1,_result:P},_init:F}},Bt.memo=function(P,H){return{$$typeof:f,type:P,compare:H===void 0?null:H}},Bt.startTransition=function(P){var H=C.T,U={};C.T=U;try{var D=P(),$=C.S;$!==null&&$(U,D),typeof D=="object"&&D!==null&&typeof D.then=="function"&&D.then(A,ae)}catch(G){ae(G)}finally{H!==null&&U.types!==null&&(H.types=U.types),C.T=H}},Bt.unstable_useCacheRefresh=function(){return C.H.useCacheRefresh()},Bt.use=function(P){return C.H.use(P)},Bt.useActionState=function(P,H,U){return C.H.useActionState(P,H,U)},Bt.useCallback=function(P,H){return C.H.useCallback(P,H)},Bt.useContext=function(P){return C.H.useContext(P)},Bt.useDebugValue=function(){},Bt.useDeferredValue=function(P,H){return C.H.useDeferredValue(P,H)},Bt.useEffect=function(P,H){return C.H.useEffect(P,H)},Bt.useEffectEvent=function(P){return C.H.useEffectEvent(P)},Bt.useId=function(){return C.H.useId()},Bt.useImperativeHandle=function(P,H,U){return C.H.useImperativeHandle(P,H,U)},Bt.useInsertionEffect=function(P,H){return C.H.useInsertionEffect(P,H)},Bt.useLayoutEffect=function(P,H){return C.H.useLayoutEffect(P,H)},Bt.useMemo=function(P,H){return C.H.useMemo(P,H)},Bt.useOptimistic=function(P,H){return C.H.useOptimistic(P,H)},Bt.useReducer=function(P,H,U){return C.H.useReducer(P,H,U)},Bt.useRef=function(P){return C.H.useRef(P)},Bt.useState=function(P){return C.H.useState(P)},Bt.useSyncExternalStore=function(P,H,U){return C.H.useSyncExternalStore(P,H,U)},Bt.useTransition=function(){return C.H.useTransition()},Bt.version="19.2.3",Bt}var C$;function EN(){return C$||(C$=1,bE.exports=Vre()),bE.exports}var y=EN();const le=Um(y),Ec=QY({__proto__:null,default:le},[y]);function JS(e,t){if(!e)throw new Error(t)}ze(JS,"assert");var R$=3e3,Gre=5e3;function xB(e){return{name:e.name,version:e.version,uri:e.websiteUrl,logo_uri:e.icons?.[0]?.src}}ze(xB,"deriveClientConfigFromClientInfo");function EB(e){const n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("oauth discovery failed")||n.includes("oauth-authorization-server")||n.includes("not valid json")||n.includes("404")&&(n.includes("openid-configuration")||n.includes("oauth-protected-resources")||n.includes("oauth-authorization-url")||n.includes("register"))||n.includes("invalid oauth error response")&&n.includes("not found")}ze(EB,"isOAuthDiscoveryFailure");function SB(e){const{url:t,enabled:n=!0,callbackUrl:r=typeof window<"u"?Du(new URL("/oauth/callback",window.location.origin).toString()):"/oauth/callback",storageKeyPrefix:a="mcp:auth",clientConfig:o={},headers:i,customHeaders:l,proxyConfig:u,autoProxyFallback:f=!0,debug:m=!1,autoRetry:h=!1,autoReconnect:g=R$,transportType:b="auto",preventAutoAuth:E=!0,useRedirectFlow:x=!1,onPopupWindow:w,timeout:S=3e4,sseReadTimeout:_=3e5,wrapTransport:T,onNotification:k,onSampling:R,samplingCallback:A,onElicitation:C}=e,O=i??l??{};l&&!i&&console.warn('[useMcp] The "customHeaders" option is deprecated. Use "headers" instead.');const M=R??A;A&&!R&&console.warn('[useMcp] The "samplingCallback" option is deprecated. Use "onSampling" instead.');const L=y.useMemo(()=>({name:"mcp-use",title:"mcp-use",version:Sv(),description:"mcp-use is a complete TypeScript framework for building and using MCP",icons:[{src:"https://mcp-use.com/logo.png"}],websiteUrl:"https://mcp-use.com"}),[]),j=y.useMemo(()=>e.clientInfo?{...L,...e.clientInfo}:L,[e.clientInfo,L]),B=y.useMemo(()=>xB(j),[j]),K=y.useMemo(()=>o&&Object.keys(o).length>0?(console.warn("[useMcp] The 'clientConfig' option is deprecated and will be removed in a future version. Use 'clientInfo' instead. The clientConfig will be automatically derived from clientInfo."),{...B,...o}):B,[o,B]),Z=y.useMemo(()=>f?typeof f=="boolean"?{enabled:f,proxyAddress:"https://inspector.mcp-use.com/inspector/api/proxy"}:{enabled:f.enabled!==!1,proxyAddress:f.proxyAddress||"https://inspector.mcp-use.com/inspector/api/proxy"}:{enabled:!1,proxyAddress:void 0},[f]),te=y.useRef(!1),[V,Y]=y.useState(u),{gatewayUrl:F,proxyHeaders:ae}=y.useMemo(()=>{const ge=c4(t||"",V);return{gatewayUrl:V?.proxyAddress,proxyHeaders:ge.headers}},[t,V]),ee=y.useMemo(()=>t||"",[t]),P=y.useMemo(()=>({...ae,...O}),[ae,O]),[H,U]=y.useState("discovering"),[D,$]=y.useState([]),[G,W]=y.useState([]),[re,pe]=y.useState([]),[me,ne]=y.useState([]),[J,X]=y.useState(),[se,he]=y.useState(),[Te,Be]=y.useState(void 0),[$e,Ge]=y.useState([]),[dt,Ve]=y.useState(void 0),[ct,rt]=y.useState(void 0),Ee=y.useRef(null),Ce=y.useRef(null),He=y.useRef(null),st=y.useRef(!1),Je=y.useRef(!0),it=y.useRef(0),kt=y.useRef(null),Nn=y.useRef(!1),ot=y.useRef(H),zn=y.useRef(g),qt=y.useRef(null),Ye=y.useRef(null),We=y.useRef(null);y.useEffect(()=>{ot.current=H,zn.current=g},[H,g]);const ue=y.useCallback((ge,_e,...Ne)=>{const Ae=Ne.length>0?`${_e} ${Ne.map(Pe=>JSON.stringify(Pe)).join(" ")}`:_e;console[ge](`[useMcp] ${Ae}`),Je.current&&Ge(Pe=>[...Pe.slice(-100),{level:ge,message:Ae,timestamp:Date.now()}])},[]),It=y.useCallback(async(ge=!1)=>{if(ge||ue("info","Disconnecting..."),st.current=!1,kt.current&&clearTimeout(kt.current),kt.current=null,Ee.current)try{const _e="inspector-server",Ne=Ee.current.getSession(_e);Ne&&Ne._healthCheckCleanup&&(Ne._healthCheckCleanup(),Ne._healthCheckCleanup=null),Ne&&await Ee.current.closeSession(_e)}catch(_e){ge||ue("warn","Error closing session:",_e)}Ee.current=null,Je.current&&!ge&&(U("discovering"),$([]),W([]),pe([]),ne([]),Be(void 0),Ve(void 0))},[ue]),Nt=y.useCallback((ge,_e)=>{ue("error",ge,_e??"");const Ne=_e&&"code"in _e?_e.code:void 0,Ae=Z.enabled&&!V?.proxyAddress,Pe=ge.includes("CORS")||ge.includes("blocked by CORS policy")||ge.includes("Failed to fetch"),Ze=Ne===400,qe=typeof Ne=="number"&&Ne>=404&&Ne<500;if(Ae&&(Pe||Ze||qe)&&!(Ne===401||Ne===403))return ue("info",`Direct connection failed with ${Pe?"CORS error":Ze?"HTTP 400 (Bad Request)":"HTTP 4xx error"}. Trying with proxy...`),Ee.current=null,Ce.current=null,ue("debug","Cleared client and auth provider for proxy fallback"),Y({proxyAddress:Z.proxyAddress}),Je.current&&U("discovering"),setTimeout(()=>{Je.current&&Ye.current?.()},1e3),!0;if(Je.current){console.log("[useMcp] Setting state to FAILED:",ge),U("failed"),Be(ge);const tt=Ce.current?.getLastAttemptedAuthUrl();tt&&(Ve(tt),ue("info","Manual authentication URL may be available.",tt))}return st.current=!1,t&&rs.getInstance().trackUseMcpConnection({url:t,transportType:b,success:!1,errorType:_e?.name||"UnknownError",hasOAuth:!!Ce.current,hasSampling:!!M,hasElicitation:!!C}).catch(()=>{}),!1},[ue,t,b,M,C,Z,V]),jt=y.useCallback(async()=>{if(!n||!t){ue("debug",n?"No server URL provided, skipping connection.":"Connection disabled via enabled flag.");return}if(st.current){ue("debug","Connection attempt already in progress.");return}if(!Je.current){ue("debug","Connect called after unmount, aborting.");return}if(st.current=!0,it.current+=1,Be(void 0),Ve(void 0),qt.current=null,U("discovering"),ue("info",`Connecting attempt #${it.current} to ${t}...`),!Ce.current){let Ne;if(F){const Ae=new URL(F),Pe=Ae.pathname.replace(/\/proxy\/?$/,"");Ne=`${Ae.origin}${Pe}/oauth`,ue("debug",`OAuth proxy URL derived from gateway: ${Ne}`)}Ce.current=new ey(ee,{storageKeyPrefix:a,clientName:K.name,clientUri:K.uri,logoUri:K.logo_uri||"https://mcp-use.com/logo.png",callbackUrl:r,preventAutoAuth:E,useRedirectFlow:x,oauthProxyUrl:Ne,onPopupWindow:w}),ue("debug",`BrowserOAuthClientProvider initialized with URL: ${ee}, proxy: ${Ne?"enabled":"disabled"}, gateway: ${F?"enabled":"disabled"}`),Ne&&(Ce.current.installFetchInterceptor(),ue("debug","Installed OAuth fetch interceptor"))}Ee.current?ue("debug","BrowserMCPClient already exists, reusing."):(Ee.current=new Hre,ue("debug","BrowserMCPClient initialized in connect."));const ge=ze(async(Ne,Ae=!1)=>{if(!Je.current)return ue("debug","Connection attempt aborted - component unmounted"),"failed";ue("info",`Attempting connection with transport: ${Ne}`),ue("debug",`Client ref status at start of tryConnectWithTransport: ${Ee.current?"initialized":"NULL"}`);try{const Pe="inspector-server",Ze={url:t,transport:Ne==="sse"?"http":Ne,disableSseFallback:b==="http",preferSse:Ne==="sse",clientInfo:j};if(F&&(Ze.gatewayUrl=F,console.log(`[useMcp] Using proxy gateway: ${F} for target: ${t}`)),P&&Object.keys(P).length>0&&(Ze.headers=P),Ce.current){const Qe=await Ce.current.tokens();if(!Je.current)return ue("debug","Connection aborted after token fetch - component unmounted"),"failed";Qe?.access_token&&(Ze.headers={...Ze.headers,Authorization:`Bearer ${Qe.access_token}`})}if(!Ee.current){if(!Je.current)return ue("debug","Connection aborted - component unmounted, client cleaned up"),"failed";const Qe=new Error("Client not initialized - this is a bug in the connection flow");throw ue("error","Client ref is null in tryConnectWithTransport but component is still mounted"),Qe}Ee.current.addServer(Pe,{...Ze,authProvider:Ce.current,clientOptions:K,onSampling:M,samplingCallback:M,elicitationCallback:C,wrapTransport:T?Qe=>(console.log("[useMcp] Applying transport wrapper for server:",Pe,"url:",t),T(Qe,t)):void 0});const qe=await Ee.current.createSession(Pe,!1);if(!Je.current)return ue("debug","Connection aborted after session creation - component unmounted"),"failed";if(qe.on("notification",Qe=>{k?.(Qe),Qe.method==="notifications/tools/list_changed"?(ue("info","Tools list changed, auto-refreshing..."),Ln().catch(Ke=>ue("warn","Auto-refresh tools failed:",Ke))):Qe.method==="notifications/resources/list_changed"?(ue("info","Resources list changed, auto-refreshing..."),sn().catch(Ke=>ue("warn","Auto-refresh resources failed:",Ke))):Qe.method==="notifications/prompts/list_changed"&&(ue("info","Prompts list changed, auto-refreshing..."),Mn().catch(Ke=>ue("warn","Auto-refresh prompts failed:",Ke)))}),await qe.initialize(),!Je.current)return ue("debug","Connection completed but component unmounted, aborting"),"failed";if(ue("info","✅ Successfully connected to MCP server"),ue("info","Server info:",qe.connector.serverInfo),ue("info","Server capabilities:",qe.connector.serverCapabilities),console.log("[useMcp] Server info:",qe.connector.serverInfo),console.log("[useMcp] Server capabilities:",qe.connector.serverCapabilities),!Je.current)return ue("debug","Skipping state update - component unmounted"),"failed";U("ready"),qt.current=Ne;const et=ze(()=>{let Qe=null,Ke=Date.now();const St=1e4,En=3e4;return Qe=setInterval(ze(async()=>{if(!Je.current||ot.current!=="ready"){Qe&&(clearInterval(Qe),Qe=null);return}try{await qe.connector.listTools(),Ke=Date.now()}catch{const _t=Date.now()-Ke;_t>En&&(ue("warn",`Connection appears to be broken (no response for ${Math.round(_t/1e3)}s), attempting to reconnect...`),Qe&&(clearInterval(Qe),Qe=null),zn.current&&Je.current&&(U("discovering"),ue("info","Auto-reconnecting to MCP server..."),setTimeout(()=>{Je.current&&ot.current==="discovering"&&jt()},typeof zn.current=="number"?zn.current:R$)))}},"checkConnectionHealth"),St),()=>{Qe&&(clearInterval(Qe),Qe=null)}},"setupConnectionMonitoring");if(g){const Qe=et();qe._healthCheckCleanup=Qe}rs.getInstance().trackUseMcpConnection({url:t,transportType:Ne,success:!0,hasOAuth:!!Ce.current,hasSampling:!!M,hasElicitation:!!C}).catch(()=>{}),$(qe.connector.tools||[]);const Ut=await qe.connector.listAllResources();if(!Je.current)return ue("debug","Connection aborted after listing resources - component unmounted"),"failed";W(Ut.resources||[]);const tt=await qe.connector.listPrompts();if(!Je.current)return ue("debug","Connection aborted after listing prompts - component unmounted"),"failed";ne(tt.prompts||[]);const xt=qe.connector.serverInfo,Ct=qe.connector.serverCapabilities;if(xt){if(console.log("[useMcp] Server info:",xt),!Je.current)return ue("debug","Skipping state update - component unmounted"),"failed";X(xt);const Qe=(async()=>{try{const Ke=xt.icons;if(Ke&&Array.isArray(Ke)&&Ke.length>0){const St=Ke[0].src||Ke[0].url;if(St){ue("info","Server provided icon:",St);const ht=await(await fetch(St)).blob(),Fn=await new Promise((_t,Cn)=>{const en=new FileReader;en.onloadend=()=>_t(en.result),en.onerror=Cn,en.readAsDataURL(ht)});return Je.current&&(X(_t=>_t?{..._t,icon:Fn}:void 0),ue("debug","Server icon converted to base64")),Fn}}if(t){const St=await l4(t);if(!Je.current)return ue("debug","Connection aborted after favicon detection - component unmounted"),null;if(St)return X(En=>En?{...En,icon:St}:void 0),ue("debug","Favicon detected and added to serverInfo"),St}return null}catch(Ke){return ue("debug","Icon loading failed (non-critical):",Ke),null}})();He.current=Qe}if(Ct){if(console.log("[useMcp] Server capabilities:",Ct),!Je.current)return ue("debug","Skipping state update - component unmounted"),"failed";he(Ct)}if(Ce.current){const Qe=await Ce.current.tokens();if(!Je.current)return ue("debug","Connection aborted after token fetch for auth tokens - component unmounted"),"failed";if(Qe?.access_token){const Ke=Qe.expires_in?Date.now()+Qe.expires_in*1e3:void 0;if(!Je.current)return ue("debug","Skipping state update - component unmounted"),"failed";rt({access_token:Qe.access_token,token_type:Qe.token_type||"Bearer",expires_at:Ke,refresh_token:Qe.refresh_token,scope:Qe.scope})}}return"success"}catch(Pe){const Ze=Pe,qe=Ze?.message||String(Pe),et=EB(Pe),Ut=Ze.code===401||qe.includes("401")||qe.includes("Unauthorized");if(et&&O&&Object.keys(O).length>0)return Nt("Authentication failed (HTTP 401). Server does not support OAuth. Check your Authorization header value is correct."),"failed";if(Ut){if(et)return Nt("Authentication required (HTTP 401). Server does not support OAuth. Add an Authorization header in the Custom Headers section (e.g., Authorization: Bearer YOUR_API_KEY)."),"failed";if(Ce.current){if(ue("info","Authentication required. OAuth provider available."),ue("info","Waiting for user to initiate authentication flow..."),Je.current){U("pending_auth");const xt=Ce.current?.getLastAttemptedAuthUrl();xt&&(Ve(xt),ue("info","Retrieved stored auth URL for manual authentication"))}return st.current=!1,"auth_redirect"}return O&&Object.keys(O).length>0?(Nt("Authentication failed: Server returned 401 Unauthorized. Check your Authorization header value is correct."),"failed"):(Nt("Authentication required: Server returned 401 Unauthorized. Add an Authorization header in the Custom Headers section (e.g., Authorization: Bearer YOUR_API_KEY)."),"failed")}return Nt(qe,Ze instanceof Error?Ze:new Error(String(Ze)))?"auth_redirect":"failed"}},"tryConnectWithTransport");let _e="failed";if(b==="sse")ue("debug","Using SSE-only transport mode"),_e=await ge("sse");else if(b==="http")ue("debug","Using HTTP-only transport mode"),_e=await ge("http");else{ue("debug","Using auto transport mode (HTTP with SSE fallback)");const Ne=await ge("http");Ne==="fallback"&&Je.current&&ot.current!=="authenticating"?(ue("info","HTTP failed, attempting SSE fallback..."),_e=await ge("sse")):_e=Ne}(_e==="success"||_e==="failed"||_e==="auth_redirect")&&(st.current=!1),ue("debug",`Connection sequence finished with status: ${_e}`)},[ue,Nt,It,t,a,r,K.name,K.version,K.uri,K.logo_uri,O,b,E,x,w,n,S,_,j,F,P,ee]);y.useEffect(()=>{Ye.current=jt,We.current=Nt},[jt,Nt]);const Pt=y.useCallback(async(ge,_e,Ne)=>{if(ot.current!=="ready"||!Ee.current)throw new Error(`MCP client is not ready (current state: ${H}). Cannot call tool "${ge}".`);ue("info",`Calling tool: ${ge}`,_e);const Ae=Date.now();try{const Ze=Ee.current.getSession("inspector-server");if(!Ze)throw new Error("No active session found");const qe=await Ze.connector.callTool(ge,_e||{},Ne);return ue("info",`Tool "${ge}" call successful:`,qe),rs.getInstance().trackUseMcpToolCall({toolName:ge,success:!0,executionTimeMs:Date.now()-Ae}).catch(()=>{}),qe}catch(Pe){throw ue("error",`Tool "${ge}" call failed:`,Pe),rs.getInstance().trackUseMcpToolCall({toolName:ge,success:!1,errorType:Pe instanceof Error?Pe.name:"UnknownError",executionTimeMs:Date.now()-Ae}).catch(()=>{}),Pe}},[H]),Xt=y.useCallback(()=>{ot.current==="failed"?(ue("info","Retry requested..."),Ye.current?.()):ue("warn",`Retry called but state is not 'failed' (state: ${ot.current}). Ignoring.`)},[ue]),xn=y.useCallback(async()=>{ue("info","Manual authentication requested...");const ge=ot.current;if(ge==="failed")ue("info","Attempting to reconnect and authenticate via retry..."),Xt();else if(ge==="pending_auth"){ue("info","Proceeding with authentication from pending state...");try{JS(Ce.current,"Auth Provider not available for manual auth"),JS(t,"Server URL is required for authentication"),ue("info","Initiating OAuth flow (preserving existing state)..."),U("authenticating");let _e;if(F){const qe=new URL(F),et=qe.pathname.replace(/\/proxy\/?$/,"");_e=`${qe.origin}${et}/oauth`}const Ne=new ey(ee,{storageKeyPrefix:a,clientName:K.name,clientUri:K.uri,logoUri:K.logo_uri||"https://mcp-use.com/logo.png",callbackUrl:r,preventAutoAuth:!1,useRedirectFlow:x,oauthProxyUrl:_e,onPopupWindow:w});_e&&!F?(Ne.installFetchInterceptor(),ue("info","Installed OAuth fetch interceptor for manual auth")):_e&&F&&ue("info","Using MCP gateway proxy for OAuth (no fetch interceptor needed)"),Ce.current=Ne,ue("info","Triggering fresh OAuth authorization...");const{auth:Ae}=await Ua(async()=>{const{auth:qe}=await Promise.resolve().then(()=>kre);return{auth:qe}},void 0),Pe=new URL(t).origin;try{await Ae(Ne,{serverUrl:Pe}),ue("info","OAuth flow completed (tokens obtained)")}catch(qe){ue("info","OAuth flow initiated (popup/redirect):",qe instanceof Error?qe.message:"Redirecting...")}const Ze=Ne.getLastAttemptedAuthUrl();Ze&&(Ve(Ze),ue("info","Updated auth URL for fallback:",Ze))}catch(_e){if(!Je.current)return;U("pending_auth"),ue("error",`Manual authentication failed: ${_e instanceof Error?_e.message:String(_e)}`)}}else if(ge==="authenticating"){ue("warn","Already attempting authentication. Check for blocked popups or wait for timeout.");const _e=Ce.current?.getLastAttemptedAuthUrl();_e&&!dt&&(Ve(_e),ue("info","Manual authentication URL retrieved:",_e))}else ue("info",`Client not in a state requiring manual authentication trigger (state: ${ge}). If needed, try disconnecting and reconnecting.`)},[ue,Xt,dt,t,x,w,a,K.name,K.uri,K.logo_uri,r,j]),ut=y.useCallback(()=>{if(Ce.current){const ge=Ce.current.clearStorage();ue("info",`Cleared ${ge} item(s) from localStorage for ${t}.`),Ve(void 0),It()}else ue("warn","Auth provider not initialized, cannot clear storage.")},[t,ue,It]),$t=y.useCallback(async()=>{if(ot.current!=="ready"||!Ee.current)throw new Error(`MCP client is not ready (current state: ${H}). Cannot list resources.`);ue("info","Listing resources");try{const _e=Ee.current.getSession("inspector-server");if(!_e)throw new Error("No active session found");const Ne=await _e.connector.listAllResources();W(Ne.resources||[]),ue("info","Resources listed successfully")}catch(ge){throw ue("error","List resources failed:",ge),ge}},[H]),Ht=y.useCallback(async ge=>{if(ot.current!=="ready"||!Ee.current)throw new Error(`MCP client is not ready (current state: ${H}). Cannot read resource.`);ue("info",`Reading resource: ${ge}`);try{const Ne=Ee.current.getSession("inspector-server");if(!Ne)throw new Error("No active session found");const Ae=await Ne.connector.readResource(ge);return ue("info","Resource read successful:",Ae),rs.getInstance().trackUseMcpResourceRead({resourceUri:ge,success:!0}).catch(()=>{}),Ae}catch(_e){throw ue("error","Resource read failed:",_e),rs.getInstance().trackUseMcpResourceRead({resourceUri:ge,success:!1,errorType:_e instanceof Error?_e.name:"UnknownError"}).catch(()=>{}),_e}},[H]),zt=y.useCallback(async()=>{if(ot.current!=="ready"||!Ee.current)throw new Error(`MCP client is not ready (current state: ${H}). Cannot list prompts.`);ue("info","Listing prompts");try{const _e=Ee.current.getSession("inspector-server");if(!_e)throw new Error("No active session found");const Ne=await _e.connector.listPrompts();ne(Ne.prompts||[]),ue("info","Prompts listed successfully")}catch(ge){throw ue("error","List prompts failed:",ge),ge}},[H]),Ln=y.useCallback(async()=>{if(ot.current!=="ready"||!Ee.current){ue("debug","Cannot refresh tools - client not ready");return}ue("debug","Refreshing tools list");try{const _e=Ee.current.getSession("inspector-server");if(!_e){ue("warn","No active session found for tools refresh");return}const Ne=await _e.connector.listTools();$(Ne||[]),ue("info","Tools list refreshed successfully")}catch(ge){ue("warn","Failed to refresh tools:",ge)}},[ue]),sn=y.useCallback(async()=>{if(ot.current!=="ready"||!Ee.current){ue("debug","Cannot refresh resources - client not ready");return}ue("debug","Refreshing resources list");try{const _e=Ee.current.getSession("inspector-server");if(!_e){ue("warn","No active session found for resources refresh");return}const Ne=await _e.connector.listAllResources();W(Ne.resources||[]),ue("info","Resources list refreshed successfully")}catch(ge){ue("warn","Failed to refresh resources:",ge)}},[ue]),Mn=y.useCallback(async()=>{if(ot.current!=="ready"||!Ee.current){ue("debug","Cannot refresh prompts - client not ready");return}ue("debug","Refreshing prompts list");try{const _e=Ee.current.getSession("inspector-server");if(!_e){ue("warn","No active session found for prompts refresh");return}const Ne=await _e.connector.listPrompts();ne(Ne.prompts||[]),ue("info","Prompts list refreshed successfully")}catch(ge){ue("warn","Failed to refresh prompts:",ge)}},[ue]),qn=y.useCallback(async()=>{ue("info","Refreshing all lists (tools, resources, prompts)"),await Promise.all([Ln(),sn(),Mn()])},[Ln,sn,Mn,ue]),oe=y.useCallback(async(ge,_e)=>{if(ot.current!=="ready"||!Ee.current)throw new Error(`MCP client is not ready (current state: ${H}). Cannot get prompt.`);ue("info",`Getting prompt: ${ge}`,_e);try{const Ae=Ee.current.getSession("inspector-server");if(!Ae)throw new Error("No active session found");const Pe=await Ae.connector.getPrompt(ge,_e||{});return ue("info",`Prompt "${ge}" retrieved successfully:`,Pe),Pe}catch(Ne){throw ue("error",`Prompt "${ge}" retrieval failed:`,Ne),Ne}},[H]);y.useEffect(()=>{const ge=ze(_e=>{_e.origin===window.location.origin&&_e.data?.type==="mcp_auth_callback"&&(ue("info","Received auth callback message.",_e.data),kt.current&&clearTimeout(kt.current),kt.current=null,_e.data.success?(ue("info","Authentication successful via popup. Reconnecting client..."),st.current&&ue("debug","Connection attempt already in progress, resetting flag to allow reconnection."),st.current=!1,setTimeout(()=>{Je.current&&(ue("debug","Initiating reconnection after successful auth callback."),Ye.current?.())},100)):We.current?.(`Authentication failed in callback: ${_e.data.error||"Unknown reason."}`))},"messageHandler");return window.addEventListener("message",ge),ue("debug","Auth callback message listener added."),()=>{window.removeEventListener("message",ge),ue("debug","Auth callback message listener removed."),kt.current&&clearTimeout(kt.current)}},[ue]),y.useEffect(()=>{te.current=!1,Y(u)},[t,u]),y.useEffect(()=>{if(Je.current=!0,!n||!t)return ue("debug",n?"No server URL provided, skipping connection.":"Connection disabled via enabled flag."),U("discovering"),()=>{Je.current=!1};if(ue("debug","useMcp mounted, initiating connection."),it.current=0,!Ce.current||Ce.current.serverUrl!==ee){let ge;if(F){const _e=new URL(F),Ne=_e.pathname.replace(/\/proxy\/?$/,"");ge=`${_e.origin}${Ne}/oauth`,ue("debug",`OAuth proxy URL derived from gateway: ${ge}`)}Ce.current=new ey(ee,{storageKeyPrefix:a,clientName:K.name,clientUri:K.uri,logoUri:K.logo_uri||"https://mcp-use.com/logo.png",callbackUrl:r,preventAutoAuth:E,useRedirectFlow:x,oauthProxyUrl:ge,onPopupWindow:w}),ue("debug",`BrowserOAuthClientProvider initialized/updated with URL: ${ee}, proxy: ${ge?"enabled":"disabled"}, gateway: ${F?"enabled":"disabled"}`),ge&&(Ce.current.installFetchInterceptor(),ue("debug","Installed OAuth fetch interceptor"))}return jt(),()=>{if(Je.current=!1,ue("debug","useMcp unmounting, disconnecting."),(ot.current==="authenticating"||ot.current==="pending_auth")&&Ce.current)try{const ge=Ce.current.clearStorage();ge>0&&ue("debug",`Cleared ${ge} OAuth state item(s) during unmount to prevent corruption`)}catch(ge){ue("debug","Error clearing OAuth state during unmount:",ge)}It(!0)}},[t,n,a,r,K.name,K.version,K.uri,K.logo_uri,x,j,ee]);const ce=y.useRef(Xt),ye=y.useRef(ue);y.useEffect(()=>{ce.current=Xt,ye.current=ue},[Xt,ue]),y.useEffect(()=>{let ge=null;if(H==="failed"&&h&&it.current>0){if(!Nn.current){Nn.current=!0;const _e=typeof h=="number"?h:Gre;ye.current("info",`Connection failed, auto-retrying in ${_e}ms...`),ge=setTimeout(()=>{Nn.current=!1,Je.current&&ot.current==="failed"&&ce.current()},_e)}}else H!=="failed"&&(Nn.current=!1);return()=>{ge&&(clearTimeout(ge),Nn.current=!1)}},[H,h]);const ke=y.useCallback(async()=>ot.current!=="ready"?(ue("warn","Cannot ensure icon loaded - not connected"),null):J?.icon?J.icon:He.current?(ue("debug","Waiting for icon to finish loading..."),await He.current):(ue("debug","No icon available and no loading in progress"),null),[J,ue]);return{state:H,name:J?.name||t||"",tools:D,resources:G,resourceTemplates:re,prompts:me,serverInfo:J,capabilities:se,error:Te,log:$e,authUrl:dt,authTokens:ct,client:Ee.current,callTool:Pt,readResource:Ht,listResources:$t,listPrompts:zt,getPrompt:oe,refreshTools:Ln,refreshResources:sn,refreshPrompts:Mn,refreshAll:qn,retry:Xt,disconnect:It,authenticate:xn,clearStorage:ut,ensureIconLoaded:ke}}ze(SB,"useMcp");var Nd,Wre=(Nd=class extends le.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("Widget Error:",t,n)}render(){return this.state.hasError?le.createElement("div",{className:"p-4 border border-red-500 bg-red-50 text-red-900 rounded-md dark:bg-red-900/20 dark:text-red-100"},le.createElement("h3",{className:"font-bold mb-2"},"Widget Error"),le.createElement("pre",{className:"text-sm whitespace-pre-wrap"},this.state.error?.message)):this.props.children}},ze(Nd,"ErrorBoundary"),Nd),$p="openai:set_globals";function Mo(e){return y.useSyncExternalStore(t=>{const n=ze(r=>{r.detail.globals[e]!==void 0&&t()},"handleSetGlobal");return typeof window<"u"&&window.addEventListener($p,n),()=>{typeof window<"u"&&window.removeEventListener($p,n)}},()=>typeof window<"u"&&window.openai?window.openai[e]:void 0)}ze(Mo,"useOpenAiGlobal");function Xd(e){const[t,n]=y.useState(()=>typeof window<"u"&&!!window.openai);y.useEffect(()=>{if(typeof window<"u"&&window.openai){n(!0);return}const L=setInterval(()=>{typeof window<"u"&&window.openai&&(n(!0),clearInterval(L))},100),j=ze(()=>{typeof window<"u"&&window.openai&&(n(!0),clearInterval(L))},"handleSetGlobals");typeof window<"u"&&window.addEventListener($p,j);const B=setTimeout(()=>{clearInterval(L),typeof window<"u"&&window.removeEventListener($p,j)},5e3);return()=>{clearInterval(L),clearTimeout(B),typeof window<"u"&&window.removeEventListener($p,j)}},[]);const r=y.useMemo(()=>t?"openai":"mcp-ui",[t]),a=typeof window<"u"?window.location.search:"",o=y.useMemo(()=>{const L=new URLSearchParams(a);return L.has("mcpUseParams")?JSON.parse(L.get("mcpUseParams")):{toolInput:{},toolOutput:{},toolId:""}},[a]),i=r==="openai"?Mo("toolInput"):o.toolInput,l=r==="openai"?Mo("toolOutput"):o.toolOutput,u=Mo("toolResponseMetadata"),f=y.useMemo(()=>{if(u&&typeof u=="object"){const L=u["mcp-use/props"];if(L)return L}return e||{}},[u,e]),m=Mo("widgetState"),h=Mo("theme"),g=Mo("displayMode"),b=Mo("safeArea"),E=Mo("maxHeight"),x=Mo("userAgent"),w=Mo("locale"),S=y.useMemo(()=>typeof window<"u"&&window.__mcpPublicUrl?window.__mcpPublicUrl.replace(/\/mcp-use\/public$/,""):"",[]),[_,T]=y.useState(null);y.useEffect(()=>{m!==void 0&&T(m)},[m]);const k=y.useCallback(async(L,j)=>{if(!window.openai?.callTool)throw new Error("window.openai.callTool is not available");return window.openai.callTool(L,j)},[]),R=y.useCallback(async L=>{if(!window.openai?.sendFollowUpMessage)throw new Error("window.openai.sendFollowUpMessage is not available");return window.openai.sendFollowUpMessage({prompt:L})},[]),A=y.useCallback(L=>{if(!window.openai?.openExternal)throw new Error("window.openai.openExternal is not available");window.openai.openExternal({href:L})},[]),C=y.useCallback(async L=>{if(!window.openai?.requestDisplayMode)throw new Error("window.openai.requestDisplayMode is not available");return window.openai.requestDisplayMode({mode:L})},[]),O=y.useCallback(async L=>{if(!window.openai?.setWidgetState)throw new Error("window.openai.setWidgetState is not available");const B=typeof L=="function"?L(m!==void 0?m:_):L;return T(B),window.openai.setWidgetState(B)},[m,_]),M=y.useMemo(()=>r==="openai"&&u===null,[r,u]);return{props:f,toolInput:i||{},output:l??null,metadata:u??null,state:_,setState:O,theme:h||"light",displayMode:g||"inline",safeArea:b||{insets:{top:0,bottom:0,left:0,right:0}},maxHeight:E||600,userAgent:x||{device:{type:"desktop"},capabilities:{hover:!0,touch:!1}},locale:w||"en",mcp_url:S,callTool:k,sendFollowUpMessage:R,openExternal:A,requestDisplayMode:C,isAvailable:t,isPending:M}}ze(Xd,"useWidget");function Kre(e){const{props:t}=Xd(e);return t}ze(Kre,"useWidgetProps");function Yre(){const{theme:e}=Xd();return e}ze(Yre,"useWidgetTheme");function Zre(e){const{state:t,setState:n}=Xd();return y.useEffect(()=>{t===null&&e!==void 0&&window.openai?.setWidgetState&&n(e)},[]),[t,n]}ze(Zre,"useWidgetState");var k$=ze(({children:e})=>{const{theme:t,isAvailable:n}=Xd();console.log("theme",t);const[r,a]=y.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");y.useEffect(()=>{if(typeof window>"u")return;const i=window.matchMedia("(prefers-color-scheme: dark)"),l=ze(u=>{a(u.matches?"dark":"light")},"handleChange");return i.addEventListener("change",l),()=>i.removeEventListener("change",l)},[]);const o=n?t:r;return y.useLayoutEffect(()=>{typeof document>"u"||(o==="dark"?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark"))},[o]),le.createElement(le.Fragment,null,e)},"ThemeProvider");function _B({children:e,className:t="",position:n="top-right",attachTo:r,showLabels:a=!0,debugger:o=!1,viewControls:i=!1}){const{props:l,output:u,metadata:f,state:m,theme:h,displayMode:g,safeArea:b,maxHeight:E,userAgent:x,locale:w,isAvailable:S,callTool:_,sendFollowUpMessage:T,openExternal:k,requestDisplayMode:R,setState:A}=Xd(),[C,O]=y.useState(!1),[M,L]=y.useState(!1),j=y.useRef(null),B=y.useRef(null),[K,Z]=y.useState([]),[te,V]=y.useState(""),[Y,F]=y.useState("get-my-city"),[ae,ee]=y.useState("{}"),[P,H]=y.useState("Test follow-up message"),[U,D]=y.useState("https://docs.mcp-use.com"),$=g==="fullscreen"&&S,G=g==="pip"&&S,W=typeof window<"u"&&window.location.pathname.includes("/inspector/api/");y.useEffect(()=>{const Ee=setTimeout(()=>{if(typeof window<"u"&&window.openai)try{const Ce=Object.keys(window.openai);Z(Ce)}catch{Z([])}else Z([])},100);return()=>{clearTimeout(Ee)}},[]);const re=h==="dark",pe=ze(()=>{const Ee=["absolute","z-[1000]","flex","gap-2","transition-opacity","duration-200","ease-in-out",C?"opacity-100":"opacity-0",C?"pointer-events-auto":"pointer-events-none"];switch(n){case"top-left":return[...Ee,"top-4","left-4"];case"top-center":return[...Ee,"top-4","left-1/2","-translate-x-1/2"];case"top-right":return[...Ee,"top-4","right-4"];case"center-left":return[...Ee,"top-1/2","left-4","-translate-y-1/2"];case"center-right":return[...Ee,"top-1/2","right-4","-translate-y-1/2"];case"bottom-left":return[...Ee,"bottom-4","left-4"];case"bottom-center":return[...Ee,"bottom-4","left-1/2","-translate-x-1/2"];case"bottom-right":return[...Ee,"bottom-4","right-4"];default:return[...Ee,"top-4","right-4"]}},"getPositionClasses"),me=ze(()=>{const Ce=b?.insets?.top?Math.max(16,b.insets.top+8):16,He=b?.insets?.right?Math.max(16,b.insets.right+8):16,st=b?.insets?.bottom?Math.max(16,b.insets.bottom+8):16,Je=b?.insets?.left?Math.max(16,b.insets.left+8):16,it={};switch(n){case"top-left":it.top=`${Ce}px`,it.left=`${Je}px`;break;case"top-center":it.top=`${Ce}px`;break;case"top-right":it.top=`${Ce}px`,it.right=`${He}px`;break;case"center-left":it.left=`${Je}px`;break;case"center-right":it.right=`${He}px`;break;case"bottom-left":it.bottom=`${st}px`,it.left=`${Je}px`;break;case"bottom-center":it.bottom=`${st}px`;break;case"bottom-right":it.bottom=`${st}px`,it.right=`${He}px`;break;default:it.top=`${Ce}px`,it.right=`${He}px`;break}return it},"getPositionOffsetStyles");y.useEffect(()=>{if(!r)return;const Ee=ze(()=>O(!0),"handleMouseEnter"),Ce=ze(()=>O(!1),"handleMouseLeave");return r.addEventListener("mouseenter",Ee),r.addEventListener("mouseleave",Ce),()=>{r.removeEventListener("mouseenter",Ee),r.removeEventListener("mouseleave",Ce)}},[r]),y.useEffect(()=>{if(!M)return;const Ee=ze(Ce=>{B.current&&!B.current.contains(Ce.target)&&L(!1)},"handleClickOutside");return document.addEventListener("mousedown",Ee),()=>{document.removeEventListener("mousedown",Ee)}},[M]),y.useEffect(()=>(M?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[M]);const ne=ze(()=>{L(!M)},"handleToggleOverlay"),J=ze(async()=>{try{V("Calling tool...");const Ee=ae.trim()?JSON.parse(ae):{},Ce=await _(Y,Ee);V(`Success: ${JSON.stringify(Ce,null,2)}`)}catch(Ee){V(`Error: ${Ee.message}`)}},"handleCallTool"),X=ze(async()=>{try{V("Sending follow-up message..."),await T(P),V("Follow-up message sent successfully")}catch(Ee){V(`Error: ${Ee.message}`)}},"handleSendFollowUpMessage"),se=ze(()=>{try{k(U),V(`Opened external link: ${U}`)}catch(Ee){V(`Error: ${Ee.message}`)}},"handleOpenExternal"),he=ze(async Ee=>{try{V(`Requesting display mode: ${Ee}...`);const Ce=await R(Ee);V(`Display mode granted: ${Ce.mode}`)}catch(Ce){V(`Error: ${Ce.message}`)}},"handleRequestDisplayMode"),Te=ze(async()=>{try{const Ee=m?{...m,debugTimestamp:new Date().toISOString()}:{debugTimestamp:new Date().toISOString()};V("Setting state..."),await A(Ee),V(`State updated: ${JSON.stringify(Ee,null,2)}`)}catch(Ee){V(`Error: ${Ee.message}`)}},"handleSetState"),Be=ze(async()=>{try{await R("fullscreen")}catch(Ee){console.error("Failed to go fullscreen:",Ee)}},"handleFullscreen"),$e=ze(async()=>{try{await R("pip")}catch(Ee){console.error("Failed to go pip:",Ee)}},"handlePip"),Ge=ze(()=>{const Ee=["absolute","px-2","py-1","bg-black/90","text-white","rounded","text-xs","whitespace-nowrap","pointer-events-none","transition-opacity","duration-200","ease-in-out"];switch(n){case"top-right":return[...Ee,"top-full","right-0","mt-2"];case"top-left":return[...Ee,"top-full","left-0","mt-2"];case"top-center":return[...Ee,"top-full","left-1/2","-translate-x-1/2","mt-2"];case"bottom-right":return[...Ee,"bottom-full","right-0","mb-2"];case"bottom-left":return[...Ee,"bottom-full","left-0","mb-2"];case"bottom-center":return[...Ee,"bottom-full","left-1/2","-translate-x-1/2","mb-2"];case"center-left":return[...Ee,"left-full","top-1/2","-translate-y-1/2","ml-2"];case"center-right":return[...Ee,"right-full","top-1/2","-translate-y-1/2","mr-2"];default:return[...Ee,"top-full","right-0","mt-2"]}},"getTooltipClasses"),dt=ze(({onClick:Ee,label:Ce,children:He})=>{const[st,Je]=y.useState(!1),it=Ge();return le.createElement("button",{className:`p-2 ${re?"bg-white/10 hover:bg-white/20":"bg-black/70 hover:bg-black/90"} text-white border-none rounded-lg cursor-pointer flex items-center justify-center w-8 h-8 transition-colors duration-200 backdrop-blur-md ${re?"shadow-[0_2px_8px_rgba(0,0,0,0.3)]":"shadow-[0_2px_8px_rgba(0,0,0,0.2)]"} relative`,onMouseEnter:()=>Je(!0),onMouseLeave:()=>Je(!1),onClick:Ee,"aria-label":Ce},le.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"block"},He),a&&le.createElement("span",{className:`${it.join(" ")} ${st?"opacity-100":"opacity-0"}`},Ce))},"IconButton"),Ve=ze(Ee=>{if(Ee===null)return"null";if(Ee===void 0)return"undefined";if(typeof Ee=="object")try{return JSON.stringify(Ee,null,2)}catch{return String(Ee)}return String(Ee)},"formatValue"),ct=ze(Ee=>Ee?`${Ee.device?.type||"unknown"}`:"N/A","formatUserAgent"),rt=ze(Ee=>{if(!Ee?.insets)return"N/A";const{top:Ce,bottom:He,left:st,right:Je}=Ee.insets;return`T:${Ce} B:${He} L:${st} R:${Je}`},"formatSafeArea");return le.createElement(le.Fragment,null,le.createElement("div",{ref:j,className:`${t} relative h-fit`,onMouseEnter:()=>!r&&O(!0),onMouseLeave:()=>!r&&O(!1)},le.createElement("div",{className:pe().join(" "),style:me()},!W&&le.createElement(le.Fragment,null,!$&&!G&&le.createElement(le.Fragment,null,(i===!0||i==="fullscreen")&&le.createElement(dt,{onClick:Be,label:"Fullscreen"},le.createElement("path",{d:"M15 3h6v6"}),le.createElement("path",{d:"m21 3-7 7"}),le.createElement("path",{d:"m3 21 7-7"}),le.createElement("path",{d:"M9 21H3v-6"})),(i===!0||i==="pip")&&le.createElement(dt,{onClick:$e,label:"Picture in Picture"},le.createElement("path",{d:"M21 9V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h4"}),le.createElement("rect",{width:"10",height:"7",x:"12",y:"13",rx:"2"}))),o&&le.createElement(dt,{onClick:ne,label:"Debug Info"},le.createElement("path",{d:"M12 20v-9"}),le.createElement("path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z"}),le.createElement("path",{d:"M14.12 3.88 16 2"}),le.createElement("path",{d:"M21 21a4 4 0 0 0-3.81-4"}),le.createElement("path",{d:"M21 5a4 4 0 0 1-3.55 3.97"}),le.createElement("path",{d:"M22 13h-4"}),le.createElement("path",{d:"M3 21a4 4 0 0 1 3.81-4"}),le.createElement("path",{d:"M3 5a4 4 0 0 0 3.55 3.97"}),le.createElement("path",{d:"M6 13H2"}),le.createElement("path",{d:"m8 2 1.88 1.88"}),le.createElement("path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13"})))),e),M&&o&&le.createElement("div",{ref:B,className:"fixed inset-0 bg-black text-white font-mono text-xs z-[10000] overflow-auto p-4",onClick:Ee=>{Ee.target===B.current&&L(!1)}},le.createElement("button",{onClick:()=>L(!1),className:"absolute top-4 right-4 bg-white/10 text-white border-none rounded w-8 h-8 cursor-pointer flex items-center justify-center text-lg leading-none","aria-label":"Close"},"×"),le.createElement("div",{className:"max-w-[1200px] mx-auto pt-10"},le.createElement("h1",{className:"text-lg font-bold mb-4 border-b border-gray-700 pb-2"},"Debug Info"),le.createElement("table",{className:"w-full border-collapse border-spacing-0"},le.createElement("tbody",null,le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Props"),le.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},Ve(l))),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Output"),le.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},Ve(u))),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Metadata"),le.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},Ve(f))),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"State"),le.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},Ve(m))),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Theme"),le.createElement("td",{className:"p-2"},h)),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Display Mode"),le.createElement("td",{className:"p-2"},g)),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Locale"),le.createElement("td",{className:"p-2"},w)),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Max Height"),le.createElement("td",{className:"p-2"},E,"px")),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"User Agent"),le.createElement("td",{className:"p-2"},ct(x))),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Safe Area"),le.createElement("td",{className:"p-2"},rt(b))),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"API Available"),le.createElement("td",{className:"p-2"},S?"Yes":"No")),le.createElement("tr",{className:"border-b border-gray-700"},le.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"window.openai Keys"),le.createElement("td",{className:"p-2"},K.length>0?K.join(", "):"N/A")))),le.createElement("h2",{className:"text-base font-bold mt-8 mb-4 border-b border-gray-700 pb-2"},"Actions"),le.createElement("div",{className:"flex flex-col gap-3"},le.createElement("div",{className:"flex gap-2 items-center"},le.createElement("input",{type:"text",value:Y,onChange:Ee=>F(Ee.target.value),placeholder:"Tool name",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs w-[150px]"}),le.createElement("input",{type:"text",value:ae,onChange:Ee=>ee(Ee.target.value),placeholder:'{"key": "value"}',className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),le.createElement("button",{onClick:J,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Call Tool")),le.createElement("div",{className:"flex gap-2 items-center"},le.createElement("input",{type:"text",value:P,onChange:Ee=>H(Ee.target.value),placeholder:"Follow-up message",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),le.createElement("button",{onClick:X,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Send Follow-Up")),le.createElement("div",{className:"flex gap-2 items-center"},le.createElement("input",{type:"text",value:U,onChange:Ee=>D(Ee.target.value),placeholder:"External URL",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),le.createElement("button",{onClick:se,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Open Link")),le.createElement("div",{className:"flex gap-2 items-center"},le.createElement("span",{className:"w-[150px] text-xs"},"Display Mode:"),le.createElement("button",{onClick:()=>he("inline"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"Inline"),le.createElement("button",{onClick:()=>he("pip"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"PiP"),le.createElement("button",{onClick:()=>he("fullscreen"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"Fullscreen")),le.createElement("div",{className:"flex gap-2 items-center"},le.createElement("button",{onClick:Te,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Set State (Add Timestamp)")),te&&le.createElement("div",{className:"mt-2 p-2 bg-[#1a1a1a] border border-gray-700 rounded whitespace-pre-wrap break-all text-[11px] max-h-[200px] overflow-auto"},le.createElement("div",{className:"font-bold mb-1 text-gray-400"},"Result:"),te,le.createElement("button",{onClick:()=>V(""),className:"mt-2 py-1 px-2 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-[11px]"},"Clear"))))))}ze(_B,"WidgetControls");function TB(){if(typeof window>"u")return"/";const t=window.location.pathname.match(/^(\/inspector\/api\/dev-widget\/[^/]+)/);return t?t[1]:"/"}ze(TB,"getBasename");var qre=150,Xre=5;function Jre({children:e,debugger:t=!1,viewControls:n=!1,autoSize:r=!1}){const a=TB(),o=y.useRef(null),i=y.useRef(0),l=y.useRef(null),u=y.useRef(!1),[f,m]=y.useState(null),[h,g]=y.useState(null),[b,E]=y.useState(!0);y.useEffect(()=>{let _=!0;return(async()=>{try{const T=await Ua(()=>import("./index-DNAI7hZM.js"),[]);_&&(m(()=>T.BrowserRouter),E(!1))}catch{_&&(g(new Error(`❌ react-router not installed!
36
36
 
37
37
  To use MCP widgets with McpUseProvider, you need to install:
38
38
 
@@ -88,7 +88,7 @@ Error generating stack: `+v.message+`
88
88
  `)},uU=function(){var e=parseInt(document.body.getAttribute(qu)||"0",10);return isFinite(e)?e:0},zie=function(){y.useEffect(function(){return document.body.setAttribute(qu,(uU()+1).toString()),function(){var e=uU()-1;e<=0?document.body.removeAttribute(qu):document.body.setAttribute(qu,e.toString())}},[])},Fie=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,a=r===void 0?"margin":r;zie();var o=y.useMemo(function(){return Pie(a)},[a]);return y.createElement($ie,{styles:Uie(o,!t,a,n?"":"!important")})},o_=!1;if(typeof window<"u")try{var Rb=Object.defineProperty({},"passive",{get:function(){return o_=!0,!0}});window.addEventListener("test",Rb,Rb),window.removeEventListener("test",Rb,Rb)}catch{o_=!1}var gu=o_?{passive:!1}:!1,Bie=function(e){return e.tagName==="TEXTAREA"},L5=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Bie(e)&&n[t]==="visible")},Hie=function(e){return L5(e,"overflowY")},Vie=function(e){return L5(e,"overflowX")},dU=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=M5(e,r);if(a){var o=j5(e,r),i=o[1],l=o[2];if(i>l)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Gie=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},Wie=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},M5=function(e,t){return e==="v"?Hie(t):Vie(t)},j5=function(e,t){return e==="v"?Gie(t):Wie(t)},Kie=function(e,t){return e==="h"&&t==="rtl"?-1:1},Yie=function(e,t,n,r,a){var o=Kie(e,window.getComputedStyle(t).direction),i=o*r,l=n.target,u=t.contains(l),f=!1,m=i>0,h=0,g=0;do{if(!l)break;var b=j5(e,l),E=b[0],x=b[1],w=b[2],S=x-w-o*E;(E||S)&&M5(e,l)&&(h+=S,g+=E);var _=l.parentNode;l=_&&_.nodeType===Node.DOCUMENT_FRAGMENT_NODE?_.host:_}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(m&&Math.abs(h)<1||!m&&Math.abs(g)<1)&&(f=!0),f},kb=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},fU=function(e){return[e.deltaX,e.deltaY]},pU=function(e){return e&&"current"in e?e.current:e},Zie=function(e,t){return e[0]===t[0]&&e[1]===t[1]},qie=function(e){return`
89
89
  .block-interactivity-`.concat(e,` {pointer-events: none;}
90
90
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
91
- `)},Xie=0,bu=[];function Jie(e){var t=y.useRef([]),n=y.useRef([0,0]),r=y.useRef(),a=y.useState(Xie++)[0],o=y.useState(D5)[0],i=y.useRef(e);y.useEffect(function(){i.current=e},[e]),y.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var x=vie([e.lockRef.current],(e.shards||[]).map(pU),!0).filter(Boolean);return x.forEach(function(w){return w.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),x.forEach(function(w){return w.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var l=y.useCallback(function(x,w){if("touches"in x&&x.touches.length===2||x.type==="wheel"&&x.ctrlKey)return!i.current.allowPinchZoom;var S=kb(x),_=n.current,T="deltaX"in x?x.deltaX:_[0]-S[0],k="deltaY"in x?x.deltaY:_[1]-S[1],R,A=x.target,C=Math.abs(T)>Math.abs(k)?"h":"v";if("touches"in x&&C==="h"&&A.type==="range")return!1;var O=window.getSelection(),M=O&&O.anchorNode,L=M?M===A||M.contains(A):!1;if(L)return!1;var j=dU(C,A);if(!j)return!0;if(j?R=C:(R=C==="v"?"h":"v",j=dU(C,A)),!j)return!1;if(!r.current&&"changedTouches"in x&&(T||k)&&(r.current=R),!R)return!0;var B=r.current||R;return Yie(B,w,x,B==="h"?T:k)},[]),u=y.useCallback(function(x){var w=x;if(!(!bu.length||bu[bu.length-1]!==o)){var S="deltaY"in w?fU(w):kb(w),_=t.current.filter(function(R){return R.name===w.type&&(R.target===w.target||w.target===R.shadowParent)&&Zie(R.delta,S)})[0];if(_&&_.should){w.cancelable&&w.preventDefault();return}if(!_){var T=(i.current.shards||[]).map(pU).filter(Boolean).filter(function(R){return R.contains(w.target)}),k=T.length>0?l(w,T[0]):!i.current.noIsolation;k&&w.cancelable&&w.preventDefault()}}},[]),f=y.useCallback(function(x,w,S,_){var T={name:x,delta:w,target:S,should:_,shadowParent:Qie(S)};t.current.push(T),setTimeout(function(){t.current=t.current.filter(function(k){return k!==T})},1)},[]),m=y.useCallback(function(x){n.current=kb(x),r.current=void 0},[]),h=y.useCallback(function(x){f(x.type,fU(x),x.target,l(x,e.lockRef.current))},[]),g=y.useCallback(function(x){f(x.type,kb(x),x.target,l(x,e.lockRef.current))},[]);y.useEffect(function(){return bu.push(o),e.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:g}),document.addEventListener("wheel",u,gu),document.addEventListener("touchmove",u,gu),document.addEventListener("touchstart",m,gu),function(){bu=bu.filter(function(x){return x!==o}),document.removeEventListener("wheel",u,gu),document.removeEventListener("touchmove",u,gu),document.removeEventListener("touchstart",m,gu)}},[]);var b=e.removeScrollBar,E=e.inert;return y.createElement(y.Fragment,null,E?y.createElement(o,{styles:qie(a)}):null,b?y.createElement(Fie,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Qie(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const ele=Rie(O5,Jie);var Xm=y.forwardRef(function(e,t){return y.createElement(Zv,as({},e,{ref:t,sideCar:ele}))});Xm.classNames=Zv.classNames;var s_=["Enter"," "],tle=["ArrowDown","PageUp","Home"],P5=["ArrowUp","PageDown","End"],nle=[...tle,...P5],rle={ltr:[...s_,"ArrowRight"],rtl:[...s_,"ArrowLeft"]},ale={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Jm="Menu",[om,ole,sle]=NN(Jm),[Sc,$5]=qo(Jm,[sle,hl,_5]),qv=hl(),U5=_5(),[ile,_c]=Sc(Jm),[lle,Qm]=Sc(Jm),z5=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:o,modal:i=!0}=e,l=qv(t),[u,f]=y.useState(null),m=y.useRef(!1),h=ps(o),g=CN(a);return y.useEffect(()=>{const b=()=>{m.current=!0,document.addEventListener("pointerdown",E,{capture:!0,once:!0}),document.addEventListener("pointermove",E,{capture:!0,once:!0})},E=()=>m.current=!1;return document.addEventListener("keydown",b,{capture:!0}),()=>{document.removeEventListener("keydown",b,{capture:!0}),document.removeEventListener("pointerdown",E,{capture:!0}),document.removeEventListener("pointermove",E,{capture:!0})}},[]),d.jsx(Gv,{...l,children:d.jsx(ile,{scope:t,open:n,onOpenChange:h,content:u,onContentChange:f,children:d.jsx(lle,{scope:t,onClose:y.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:m,dir:g,modal:i,children:r})})})};z5.displayName=Jm;var cle="MenuAnchor",PN=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,a=qv(n);return d.jsx(Zm,{...a,...r,ref:t})});PN.displayName=cle;var $N="MenuPortal",[ule,F5]=Sc($N,{forceMount:void 0}),B5=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=e,o=_c($N,t);return d.jsx(ule,{scope:t,forceMount:n,children:d.jsx(ao,{present:n||o.open,children:d.jsx(af,{asChild:!0,container:a,children:r})})})};B5.displayName=$N;var Eo="MenuContent",[dle,UN]=Sc(Eo),H5=y.forwardRef((e,t)=>{const n=F5(Eo,e.__scopeMenu),{forceMount:r=n.forceMount,...a}=e,o=_c(Eo,e.__scopeMenu),i=Qm(Eo,e.__scopeMenu);return d.jsx(om.Provider,{scope:e.__scopeMenu,children:d.jsx(ao,{present:r||o.open,children:d.jsx(om.Slot,{scope:e.__scopeMenu,children:i.modal?d.jsx(fle,{...a,ref:t}):d.jsx(ple,{...a,ref:t})})})})}),fle=y.forwardRef((e,t)=>{const n=_c(Eo,e.__scopeMenu),r=y.useRef(null),a=gn(t,r);return y.useEffect(()=>{const o=r.current;if(o)return Yv(o)},[]),d.jsx(zN,{...e,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:lt(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),ple=y.forwardRef((e,t)=>{const n=_c(Eo,e.__scopeMenu);return d.jsx(zN,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),mle=cc("MenuContent.ScrollLock"),zN=y.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:a,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:b,disableOutsideScroll:E,...x}=e,w=_c(Eo,n),S=Qm(Eo,n),_=qv(n),T=U5(n),k=ole(n),[R,A]=y.useState(null),C=y.useRef(null),O=gn(t,C,w.onContentChange),M=y.useRef(0),L=y.useRef(""),j=y.useRef(0),B=y.useRef(null),K=y.useRef("right"),Z=y.useRef(0),te=E?Xm:y.Fragment,V=E?{as:mle,allowPinchZoom:!0}:void 0,Y=ae=>{const ee=L.current+ae,P=k().filter(W=>!W.disabled),H=document.activeElement,U=P.find(W=>W.ref.current===H)?.textValue,D=P.map(W=>W.textValue),$=Nle(D,ee,U),G=P.find(W=>W.textValue===$)?.ref.current;(function W(re){L.current=re,window.clearTimeout(M.current),re!==""&&(M.current=window.setTimeout(()=>W(""),1e3))})(ee),G&&setTimeout(()=>G.focus())};y.useEffect(()=>()=>window.clearTimeout(M.current),[]),zv();const F=y.useCallback(ae=>K.current===B.current?.side&&Rle(ae,B.current?.area),[]);return d.jsx(dle,{scope:n,searchRef:L,onItemEnter:y.useCallback(ae=>{F(ae)&&ae.preventDefault()},[F]),onItemLeave:y.useCallback(ae=>{F(ae)||(C.current?.focus(),A(null))},[F]),onTriggerLeave:y.useCallback(ae=>{F(ae)&&ae.preventDefault()},[F]),pointerGraceTimerRef:j,onPointerGraceIntentChange:y.useCallback(ae=>{B.current=ae},[]),children:d.jsx(te,{...V,children:d.jsx(Km,{asChild:!0,trapped:a,onMountAutoFocus:lt(o,ae=>{ae.preventDefault(),C.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:d.jsx(tf,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:b,children:d.jsx(mie,{asChild:!0,...T,dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:R,onCurrentTabStopIdChange:A,onEntryFocus:lt(u,ae=>{S.isUsingKeyboardRef.current||ae.preventDefault()}),preventScrollOnEntryFocus:!0,children:d.jsx(Wv,{role:"menu","aria-orientation":"vertical","data-state":oH(w.open),"data-radix-menu-content":"",dir:S.dir,..._,...x,ref:O,style:{outline:"none",...x.style},onKeyDown:lt(x.onKeyDown,ae=>{const P=ae.target.closest("[data-radix-menu-content]")===ae.currentTarget,H=ae.ctrlKey||ae.altKey||ae.metaKey,U=ae.key.length===1;P&&(ae.key==="Tab"&&ae.preventDefault(),!H&&U&&Y(ae.key));const D=C.current;if(ae.target!==D||!nle.includes(ae.key))return;ae.preventDefault();const G=k().filter(W=>!W.disabled).map(W=>W.ref.current);P5.includes(ae.key)&&G.reverse(),_le(G)}),onBlur:lt(e.onBlur,ae=>{ae.currentTarget.contains(ae.target)||(window.clearTimeout(M.current),L.current="")}),onPointerMove:lt(e.onPointerMove,sm(ae=>{const ee=ae.target,P=Z.current!==ae.clientX;if(ae.currentTarget.contains(ee)&&P){const H=ae.clientX>Z.current?"right":"left";K.current=H,Z.current=ae.clientX}}))})})})})})})});H5.displayName=Eo;var hle="MenuGroup",FN=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(Zt.div,{role:"group",...r,ref:t})});FN.displayName=hle;var gle="MenuLabel",V5=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(Zt.div,{...r,ref:t})});V5.displayName=gle;var Wy="MenuItem",mU="menu.itemSelect",Xv=y.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...a}=e,o=y.useRef(null),i=Qm(Wy,e.__scopeMenu),l=UN(Wy,e.__scopeMenu),u=gn(t,o),f=y.useRef(!1),m=()=>{const h=o.current;if(!n&&h){const g=new CustomEvent(mU,{bubbles:!0,cancelable:!0});h.addEventListener(mU,b=>r?.(b),{once:!0}),JB(h,g),g.defaultPrevented?f.current=!1:i.onClose()}};return d.jsx(G5,{...a,ref:u,disabled:n,onClick:lt(e.onClick,m),onPointerDown:h=>{e.onPointerDown?.(h),f.current=!0},onPointerUp:lt(e.onPointerUp,h=>{f.current||h.currentTarget?.click()}),onKeyDown:lt(e.onKeyDown,h=>{const g=l.searchRef.current!=="";n||g&&h.key===" "||s_.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});Xv.displayName=Wy;var G5=y.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:a,...o}=e,i=UN(Wy,n),l=U5(n),u=y.useRef(null),f=gn(t,u),[m,h]=y.useState(!1),[g,b]=y.useState("");return y.useEffect(()=>{const E=u.current;E&&b((E.textContent??"").trim())},[o.children]),d.jsx(om.ItemSlot,{scope:n,disabled:r,textValue:a??g,children:d.jsx(hie,{asChild:!0,...l,focusable:!r,children:d.jsx(Zt.div,{role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...o,ref:f,onPointerMove:lt(e.onPointerMove,sm(E=>{r?i.onItemLeave(E):(i.onItemEnter(E),E.defaultPrevented||E.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:lt(e.onPointerLeave,sm(E=>i.onItemLeave(E))),onFocus:lt(e.onFocus,()=>h(!0)),onBlur:lt(e.onBlur,()=>h(!1))})})})}),ble="MenuCheckboxItem",W5=y.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...a}=e;return d.jsx(X5,{scope:e.__scopeMenu,checked:n,children:d.jsx(Xv,{role:"menuitemcheckbox","aria-checked":Ky(n)?"mixed":n,...a,ref:t,"data-state":HN(n),onSelect:lt(a.onSelect,()=>r?.(Ky(n)?!0:!n),{checkForDefaultPrevented:!1})})})});W5.displayName=ble;var K5="MenuRadioGroup",[yle,vle]=Sc(K5,{value:void 0,onValueChange:()=>{}}),Y5=y.forwardRef((e,t)=>{const{value:n,onValueChange:r,...a}=e,o=ps(r);return d.jsx(yle,{scope:e.__scopeMenu,value:n,onValueChange:o,children:d.jsx(FN,{...a,ref:t})})});Y5.displayName=K5;var Z5="MenuRadioItem",q5=y.forwardRef((e,t)=>{const{value:n,...r}=e,a=vle(Z5,e.__scopeMenu),o=n===a.value;return d.jsx(X5,{scope:e.__scopeMenu,checked:o,children:d.jsx(Xv,{role:"menuitemradio","aria-checked":o,...r,ref:t,"data-state":HN(o),onSelect:lt(r.onSelect,()=>a.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});q5.displayName=Z5;var BN="MenuItemIndicator",[X5,wle]=Sc(BN,{checked:!1}),J5=y.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...a}=e,o=wle(BN,n);return d.jsx(ao,{present:r||Ky(o.checked)||o.checked===!0,children:d.jsx(Zt.span,{...a,ref:t,"data-state":HN(o.checked)})})});J5.displayName=BN;var xle="MenuSeparator",Q5=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(Zt.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Q5.displayName=xle;var Ele="MenuArrow",eH=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,a=qv(n);return d.jsx(Kv,{...a,...r,ref:t})});eH.displayName=Ele;var Sle="MenuSub",[UTe,tH]=Sc(Sle),Np="MenuSubTrigger",nH=y.forwardRef((e,t)=>{const n=_c(Np,e.__scopeMenu),r=Qm(Np,e.__scopeMenu),a=tH(Np,e.__scopeMenu),o=UN(Np,e.__scopeMenu),i=y.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=o,f={__scopeMenu:e.__scopeMenu},m=y.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return y.useEffect(()=>m,[m]),y.useEffect(()=>{const h=l.current;return()=>{window.clearTimeout(h),u(null)}},[l,u]),d.jsx(PN,{asChild:!0,...f,children:d.jsx(G5,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":a.contentId,"data-state":oH(n.open),...e,ref:fs(t,a.onTriggerChange),onClick:h=>{e.onClick?.(h),!(e.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:lt(e.onPointerMove,sm(h=>{o.onItemEnter(h),!h.defaultPrevented&&!e.disabled&&!n.open&&!i.current&&(o.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:lt(e.onPointerLeave,sm(h=>{m();const g=n.content?.getBoundingClientRect();if(g){const b=n.content?.dataset.side,E=b==="right",x=E?-5:5,w=g[E?"left":"right"],S=g[E?"right":"left"];o.onPointerGraceIntentChange({area:[{x:h.clientX+x,y:h.clientY},{x:w,y:g.top},{x:S,y:g.top},{x:S,y:g.bottom},{x:w,y:g.bottom}],side:b}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(h),h.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:lt(e.onKeyDown,h=>{const g=o.searchRef.current!=="";e.disabled||g&&h.key===" "||rle[r.dir].includes(h.key)&&(n.onOpenChange(!0),n.content?.focus(),h.preventDefault())})})})});nH.displayName=Np;var rH="MenuSubContent",aH=y.forwardRef((e,t)=>{const n=F5(Eo,e.__scopeMenu),{forceMount:r=n.forceMount,...a}=e,o=_c(Eo,e.__scopeMenu),i=Qm(Eo,e.__scopeMenu),l=tH(rH,e.__scopeMenu),u=y.useRef(null),f=gn(t,u);return d.jsx(om.Provider,{scope:e.__scopeMenu,children:d.jsx(ao,{present:r||o.open,children:d.jsx(om.Slot,{scope:e.__scopeMenu,children:d.jsx(zN,{id:l.contentId,"aria-labelledby":l.triggerId,...a,ref:f,align:"start",side:i.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{i.isUsingKeyboardRef.current&&u.current?.focus(),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:lt(e.onFocusOutside,m=>{m.target!==l.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:lt(e.onEscapeKeyDown,m=>{i.onClose(),m.preventDefault()}),onKeyDown:lt(e.onKeyDown,m=>{const h=m.currentTarget.contains(m.target),g=ale[i.dir].includes(m.key);h&&g&&(o.onOpenChange(!1),l.trigger?.focus(),m.preventDefault())})})})})})});aH.displayName=rH;function oH(e){return e?"open":"closed"}function Ky(e){return e==="indeterminate"}function HN(e){return Ky(e)?"indeterminate":e?"checked":"unchecked"}function _le(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Tle(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Nle(e,t,n){const a=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let i=Tle(e,Math.max(o,0));a.length===1&&(i=i.filter(f=>f!==n));const u=i.find(f=>f.toLowerCase().startsWith(a.toLowerCase()));return u!==n?u:void 0}function Cle(e,t){const{x:n,y:r}=e;let a=!1;for(let o=0,i=t.length-1;o<t.length;i=o++){const l=t[o],u=t[i],f=l.x,m=l.y,h=u.x,g=u.y;m>r!=g>r&&n<(h-f)*(r-m)/(g-m)+f&&(a=!a)}return a}function Rle(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Cle(n,t)}function sm(e){return t=>t.pointerType==="mouse"?e(t):void 0}var kle=z5,Ale=PN,Ile=B5,Ole=H5,Dle=FN,Lle=V5,Mle=Xv,jle=W5,Ple=Y5,$le=q5,Ule=J5,zle=Q5,Fle=eH,Ble=nH,Hle=aH,Jv="DropdownMenu",[Vle]=qo(Jv,[$5]),Ra=$5(),[Gle,sH]=Vle(Jv),iH=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:o,onOpenChange:i,modal:l=!0}=e,u=Ra(t),f=y.useRef(null),[m,h]=Qs({prop:a,defaultProp:o??!1,onChange:i,caller:Jv});return d.jsx(Gle,{scope:t,triggerId:oa(),triggerRef:f,contentId:oa(),open:m,onOpenChange:h,onOpenToggle:y.useCallback(()=>h(g=>!g),[h]),modal:l,children:d.jsx(kle,{...u,open:m,onOpenChange:h,dir:r,modal:l,children:n})})};iH.displayName=Jv;var lH="DropdownMenuTrigger",cH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...a}=e,o=sH(lH,n),i=Ra(n);return d.jsx(Ale,{asChild:!0,...i,children:d.jsx(Zt.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...a,ref:fs(t,o.triggerRef),onPointerDown:lt(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(o.onOpenToggle(),o.open||l.preventDefault())}),onKeyDown:lt(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&o.onOpenToggle(),l.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});cH.displayName=lH;var Wle="DropdownMenuPortal",uH=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Ra(t);return d.jsx(Ile,{...r,...n})};uH.displayName=Wle;var dH="DropdownMenuContent",fH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=sH(dH,n),o=Ra(n),i=y.useRef(!1);return d.jsx(Ole,{id:a.contentId,"aria-labelledby":a.triggerId,...o,...r,ref:t,onCloseAutoFocus:lt(e.onCloseAutoFocus,l=>{i.current||a.triggerRef.current?.focus(),i.current=!1,l.preventDefault()}),onInteractOutside:lt(e.onInteractOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0,m=u.button===2||f;(!a.modal||m)&&(i.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});fH.displayName=dH;var Kle="DropdownMenuGroup",Yle=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(Dle,{...a,...r,ref:t})});Yle.displayName=Kle;var Zle="DropdownMenuLabel",pH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(Lle,{...a,...r,ref:t})});pH.displayName=Zle;var qle="DropdownMenuItem",mH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(Mle,{...a,...r,ref:t})});mH.displayName=qle;var Xle="DropdownMenuCheckboxItem",hH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(jle,{...a,...r,ref:t})});hH.displayName=Xle;var Jle="DropdownMenuRadioGroup",gH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(Ple,{...a,...r,ref:t})});gH.displayName=Jle;var Qle="DropdownMenuRadioItem",bH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx($le,{...a,...r,ref:t})});bH.displayName=Qle;var ece="DropdownMenuItemIndicator",tce=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(Ule,{...a,...r,ref:t})});tce.displayName=ece;var nce="DropdownMenuSeparator",yH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(zle,{...a,...r,ref:t})});yH.displayName=nce;var rce="DropdownMenuArrow",ace=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(Fle,{...a,...r,ref:t})});ace.displayName=rce;var oce="DropdownMenuSubTrigger",vH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(Ble,{...a,...r,ref:t})});vH.displayName=oce;var sce="DropdownMenuSubContent",wH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(Hle,{...a,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});wH.displayName=sce;var ice=iH,lce=cH,cce=uH,xH=fH,EH=pH,SH=mH,uce=hH,dce=gH,_H=bH,TH=yH,fce=vH,pce=wH;const im=ice,lm=lce,mce=dce;fce.displayName;pce.displayName;function jd({ref:e,className:t,sideOffset:n=4,...r}){return d.jsx(cce,{children:d.jsx(xH,{ref:e,sideOffset:n,className:Ue("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...r})})}jd.displayName=xH.displayName;function Jr({ref:e,className:t,inset:n,...r}){return d.jsx(SH,{ref:e,className:Ue("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",n&&"pl-8",t),...r})}Jr.displayName=SH.displayName;uce.displayName;function ay({ref:e,className:t,children:n,...r}){return d.jsx(_H,{ref:e,className:Ue("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...r,children:n})}ay.displayName=_H.displayName;function i_({ref:e,className:t,inset:n,...r}){return d.jsx(EH,{ref:e,className:Ue("px-2 py-1.5 text-sm font-semibold",n&&"pl-8",t),...r})}i_.displayName=EH.displayName;function Lu({ref:e,className:t,...n}){return d.jsx(TH,{ref:e,className:Ue("-mx-1 my-1 h-px bg-muted",t),...n})}Lu.displayName=TH.displayName;function of({message:e,className:t="",vertical:n,noBorder:r}){return d.jsx("div",{className:Ue(`mt-2 rounded-md p-6 ${t}`,!r&&"border"),children:d.jsxs("p",{className:Ue("text-sm text-muted-foreground flex items-center gap-4",n&&"flex-col"),children:[d.jsx("svg",{width:"40",height:"40",viewBox:"0 0 273 273",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:"flex-shrink-0",children:d.jsx("g",{stroke:"none",strokeWidth:"1",fill:"none",fillRule:"evenodd",children:d.jsxs("g",{transform:"translate(5.320900, 5.320900)",fillRule:"nonzero",className:"stroke-black dark:stroke-white",strokeWidth:"4",children:[d.jsx("path",{d:"M49.953025,-2.10854389 C63.26892,-2.21867124 76.6185256,2.70621155 86.9019463,12.6653164 L86.9019463,12.6653164 L87.505627,13.2592944 C97.5154947,23.2654892 102.640454,36.3074513 102.880738,49.4222247 C103.08932,77.4533067 113.877287,105.391753 135.242867,126.757333 C156.613383,148.127849 184.559216,158.914875 212.568138,159.119313 L212.568138,159.119313 L213.212264,159.134159 C225.843948,159.517566 238.363557,164.434972 248.121998,173.886137 L248.121998,173.886137 L248.725621,174.480088 C258.982114,184.732164 264.11035,198.171134 264.11035,211.6101 C264.11035,225.04592 258.984514,238.481745 248.732867,248.732867 C238.592792,258.872942 225.336706,263.997882 212.046872,264.107794 C198.731075,264.21792 185.381569,259.293085 175.098248,249.334078 L175.098248,249.334078 L174.494602,248.740134 C163.75802,238.008189 158.640853,223.784027 159.143413,209.719372 C158.258245,182.640933 147.489786,155.83332 126.828333,135.171867 C106.351297,114.694831 79.8363505,103.934873 53.0237258,102.891841 L53.0237258,102.891841 L52.2811438,102.865674 C38.4791718,103.347421 24.5325234,98.4328111 13.8776628,88.1140866 L13.8776628,88.1140866 L13.2739843,87.5201168 C3.12895117,77.3789607 -1.9984796,64.1195994 -2.10841888,50.8264755 C-2.21854669,37.5105567 2.70635908,24.1609269 12.6655135,13.8774565 L12.6655135,13.8774565 L13.2594878,13.2737797 C23.4005926,3.12880025 36.659927,-1.99860507 49.953025,-2.10854389 Z"}),d.jsx("circle",{cx:"50",cy:"212.0001",r:"52.5"}),d.jsx("circle",{cx:"212.0001",cy:"50",r:"52.5"})]})})}),e]})})}function NH({className:e,color:t,children:n,grayscaled:r=!1}){const a=y.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[1]||"0")}return r?0:.2},[t,r]),o=y.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[0]||"0.5")}return r?.3:.4},[t,r]),i=y.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[2]||"0")}return Math.floor(Math.random()*360)},[t]),l=y.useMemo(()=>t||`oklch(${Math.min(o,1)} ${a} ${i})`,[i,a,o]),u=y.useMemo(()=>`oklch(${Math.min(o*2,1)} ${a} ${i})`,[i,a,o,t]),f=y.useMemo(()=>Math.floor(Math.random()*360),[i]),m=y.useMemo(()=>"1000%",[]);return d.jsx("section",{className:Ue("relative w-full h-full overflow-hidden",e),style:{background:`${u}`},children:d.jsxs("div",{className:"isolate relative w-full h-full",children:[d.jsx("div",{className:"noise w-full h-full",style:{background:`linear-gradient(${f}deg, ${l}, transparent), url(https://grainy-gradients.vercel.app/noise.svg)`,filter:`contrast(120%) brightness(${m})`}}),n&&d.jsx("div",{className:"relative z-10 w-full h-full",children:n})]})})}var CH=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),hce="VisuallyHidden",RH=y.forwardRef((e,t)=>d.jsx(Zt.span,{...e,ref:t,style:{...CH,...e.style}}));RH.displayName=hce;var gce=RH,[Qv]=qo("Tooltip",[hl]),ew=hl(),kH="TooltipProvider",bce=700,l_="tooltip.open",[yce,VN]=Qv(kH),AH=e=>{const{__scopeTooltip:t,delayDuration:n=bce,skipDelayDuration:r=300,disableHoverableContent:a=!1,children:o}=e,i=y.useRef(!0),l=y.useRef(!1),u=y.useRef(0);return y.useEffect(()=>{const f=u.current;return()=>window.clearTimeout(f)},[]),d.jsx(yce,{scope:t,isOpenDelayedRef:i,delayDuration:n,onOpen:y.useCallback(()=>{window.clearTimeout(u.current),i.current=!1},[]),onClose:y.useCallback(()=>{window.clearTimeout(u.current),u.current=window.setTimeout(()=>i.current=!0,r)},[r]),isPointerInTransitRef:l,onPointerInTransitChange:y.useCallback(f=>{l.current=f},[]),disableHoverableContent:a,children:o})};AH.displayName=kH;var cm="Tooltip",[vce,eh]=Qv(cm),IH=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:o,disableHoverableContent:i,delayDuration:l}=e,u=VN(cm,e.__scopeTooltip),f=ew(t),[m,h]=y.useState(null),g=oa(),b=y.useRef(0),E=i??u.disableHoverableContent,x=l??u.delayDuration,w=y.useRef(!1),[S,_]=Qs({prop:r,defaultProp:a??!1,onChange:C=>{C?(u.onOpen(),document.dispatchEvent(new CustomEvent(l_))):u.onClose(),o?.(C)},caller:cm}),T=y.useMemo(()=>S?w.current?"delayed-open":"instant-open":"closed",[S]),k=y.useCallback(()=>{window.clearTimeout(b.current),b.current=0,w.current=!1,_(!0)},[_]),R=y.useCallback(()=>{window.clearTimeout(b.current),b.current=0,_(!1)},[_]),A=y.useCallback(()=>{window.clearTimeout(b.current),b.current=window.setTimeout(()=>{w.current=!0,_(!0),b.current=0},x)},[x,_]);return y.useEffect(()=>()=>{b.current&&(window.clearTimeout(b.current),b.current=0)},[]),d.jsx(Gv,{...f,children:d.jsx(vce,{scope:t,contentId:g,open:S,stateAttribute:T,trigger:m,onTriggerChange:h,onTriggerEnter:y.useCallback(()=>{u.isOpenDelayedRef.current?A():k()},[u.isOpenDelayedRef,A,k]),onTriggerLeave:y.useCallback(()=>{E?R():(window.clearTimeout(b.current),b.current=0)},[R,E]),onOpen:k,onClose:R,disableHoverableContent:E,children:n})})};IH.displayName=cm;var c_="TooltipTrigger",OH=y.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,a=eh(c_,n),o=VN(c_,n),i=ew(n),l=y.useRef(null),u=gn(t,l,a.onTriggerChange),f=y.useRef(!1),m=y.useRef(!1),h=y.useCallback(()=>f.current=!1,[]);return y.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),d.jsx(Zm,{asChild:!0,...i,children:d.jsx(Zt.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...r,ref:u,onPointerMove:lt(e.onPointerMove,g=>{g.pointerType!=="touch"&&!m.current&&!o.isPointerInTransitRef.current&&(a.onTriggerEnter(),m.current=!0)}),onPointerLeave:lt(e.onPointerLeave,()=>{a.onTriggerLeave(),m.current=!1}),onPointerDown:lt(e.onPointerDown,()=>{a.open&&a.onClose(),f.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:lt(e.onFocus,()=>{f.current||a.onOpen()}),onBlur:lt(e.onBlur,a.onClose),onClick:lt(e.onClick,a.onClose)})})});OH.displayName=c_;var GN="TooltipPortal",[wce,xce]=Qv(GN,{forceMount:void 0}),DH=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:a}=e,o=eh(GN,t);return d.jsx(wce,{scope:t,forceMount:n,children:d.jsx(ao,{present:n||o.open,children:d.jsx(af,{asChild:!0,container:a,children:r})})})};DH.displayName=GN;var Pd="TooltipContent",LH=y.forwardRef((e,t)=>{const n=xce(Pd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:a="top",...o}=e,i=eh(Pd,e.__scopeTooltip);return d.jsx(ao,{present:r||i.open,children:i.disableHoverableContent?d.jsx(MH,{side:a,...o,ref:t}):d.jsx(Ece,{side:a,...o,ref:t})})}),Ece=y.forwardRef((e,t)=>{const n=eh(Pd,e.__scopeTooltip),r=VN(Pd,e.__scopeTooltip),a=y.useRef(null),o=gn(t,a),[i,l]=y.useState(null),{trigger:u,onClose:f}=n,m=a.current,{onPointerInTransitChange:h}=r,g=y.useCallback(()=>{l(null),h(!1)},[h]),b=y.useCallback((E,x)=>{const w=E.currentTarget,S={x:E.clientX,y:E.clientY},_=Nce(S,w.getBoundingClientRect()),T=Cce(S,_),k=Rce(x.getBoundingClientRect()),R=Ace([...T,...k]);l(R),h(!0)},[h]);return y.useEffect(()=>()=>g(),[g]),y.useEffect(()=>{if(u&&m){const E=w=>b(w,m),x=w=>b(w,u);return u.addEventListener("pointerleave",E),m.addEventListener("pointerleave",x),()=>{u.removeEventListener("pointerleave",E),m.removeEventListener("pointerleave",x)}}},[u,m,b,g]),y.useEffect(()=>{if(i){const E=x=>{const w=x.target,S={x:x.clientX,y:x.clientY},_=u?.contains(w)||m?.contains(w),T=!kce(S,i);_?g():T&&(g(),f())};return document.addEventListener("pointermove",E),()=>document.removeEventListener("pointermove",E)}},[u,m,i,f,g]),d.jsx(MH,{...e,ref:o})}),[Sce,_ce]=Qv(cm,{isInside:!1}),Tce=poe("TooltipContent"),MH=y.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":a,onEscapeKeyDown:o,onPointerDownOutside:i,...l}=e,u=eh(Pd,n),f=ew(n),{onClose:m}=u;return y.useEffect(()=>(document.addEventListener(l_,m),()=>document.removeEventListener(l_,m)),[m]),y.useEffect(()=>{if(u.trigger){const h=g=>{g.target?.contains(u.trigger)&&m()};return window.addEventListener("scroll",h,{capture:!0}),()=>window.removeEventListener("scroll",h,{capture:!0})}},[u.trigger,m]),d.jsx(tf,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:h=>h.preventDefault(),onDismiss:m,children:d.jsxs(Wv,{"data-state":u.stateAttribute,...f,...l,ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[d.jsx(Tce,{children:r}),d.jsx(Sce,{scope:n,isInside:!0,children:d.jsx(gce,{id:u.contentId,role:"tooltip",children:a||r})})]})})});LH.displayName=Pd;var jH="TooltipArrow",PH=y.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,a=ew(n);return _ce(jH,n).isInside?null:d.jsx(Kv,{...a,...r,ref:t})});PH.displayName=jH;function Nce(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),a=Math.abs(t.right-e.x),o=Math.abs(t.left-e.x);switch(Math.min(n,r,a,o)){case o:return"left";case a:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Cce(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function Rce(e){const{top:t,right:n,bottom:r,left:a}=e;return[{x:a,y:t},{x:n,y:t},{x:n,y:r},{x:a,y:r}]}function kce(e,t){const{x:n,y:r}=e;let a=!1;for(let o=0,i=t.length-1;o<t.length;i=o++){const l=t[o],u=t[i],f=l.x,m=l.y,h=u.x,g=u.y;m>r!=g>r&&n<(h-f)*(r-m)/(g-m)+f&&(a=!a)}return a}function Ace(e){const t=e.slice();return t.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),Ice(t)}function Ice(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const a=e[r];for(;t.length>=2;){const o=t[t.length-1],i=t[t.length-2];if((o.x-i.x)*(a.y-i.y)>=(o.y-i.y)*(a.x-i.x))t.pop();else break}t.push(a)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const a=e[r];for(;n.length>=2;){const o=n[n.length-1],i=n[n.length-2];if((o.x-i.x)*(a.y-i.y)>=(o.y-i.y)*(a.x-i.x))n.pop();else break}n.push(a)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var Oce=AH,Dce=IH,Lce=OH,Mce=DH,jce=LH,Pce=PH;function WN({delayDuration:e=0,...t}){return d.jsx(Oce,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Wt({...e}){return d.jsx(WN,{children:d.jsx(Dce,{"data-slot":"tooltip",...e})})}function Kt({...e}){return d.jsx(Lce,{"data-slot":"tooltip-trigger",...e})}function Yt({className:e,sideOffset:t=0,children:n,...r}){return d.jsx(Mce,{children:d.jsxs(jce,{"data-slot":"tooltip-content",sideOffset:t,className:Ue("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...r,children:[n,d.jsx(Pce,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}class $ce{name="mcp_inspector_open";properties;constructor(t){this.properties={server_url:t.serverUrl,connection_count:t.connectionCount}}}class hU{name="mcp_tool_execution";properties;constructor(t){this.properties={tool_name:t.toolName,server_id:t.serverId,success:t.success,duration:t.duration,error:t.error}}}class gU{name="mcp_resource_read";properties;constructor(t){this.properties={resource_uri:t.resourceUri,server_id:t.serverId,success:t.success,error:t.error}}}class bU{name="mcp_prompt_call";properties;constructor(t){this.properties={prompt_name:t.promptName,server_id:t.serverId,success:t.success,error:t.error}}}class yU{name="mcp_chat_message";properties;constructor(t){this.properties={server_id:t.serverId,provider:t.provider,model:t.model,message_count:t.messageCount,tool_calls_count:t.toolCallsCount,success:t.success,execution_mode:t.executionMode,duration:t.duration,error:t.error}}}class Uce{name="mcp_server_added";properties;constructor(t){this.properties={server_id:t.serverId,server_url:t.serverUrl,connection_type:t.connectionType,via_proxy:t.viaProxy}}}class zce{name="mcp_command_palette_open";properties;constructor(t){this.properties={trigger:t.trigger}}}class Fce{name="mcp_tool_saved";properties;constructor(t){this.properties={tool_name:t.toolName,server_id:t.serverId}}}function LE(){try{return"0.14.4-canary.0"}catch{return"0.0.0"}}var Bce={};function ME(){try{return typeof window<"u"&&typeof document<"u"}catch{return!1}}class vU{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,r=setTimeout(()=>n.abort(),this.timeout),a=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(r),!a.ok)throw new Error(`HTTP error! status: ${a.status}`)}catch{}}}function Pi(e){return`mcp_inspector_telemetry_${e}`}class ra{static instance=null;POSTHOG_PROXY_URL="/inspector/api/tel/posthog";SCARF_PROXY_URL="/inspector/api/tel/scarf";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogClient=null;_scarfClient=null;_source="inspector";constructor(){const t=ME(),n=this.isTelemetryDisabled();if(this._source=this.getStoredSource()||"inspector",n)this._posthogClient=null,this._scarfClient=null;else if(!t)this._posthogClient=null,this._scarfClient=null;else{try{this._posthogClient=new vU(this.POSTHOG_PROXY_URL,3e3)}catch{this._posthogClient=null}try{this._scarfClient=new vU(this.SCARF_PROXY_URL,3e3)}catch{this._scarfClient=null}}}isTelemetryDisabled(){return typeof localStorage<"u"&&localStorage.getItem(Pi("disabled"))==="true"||typeof process<"u"&&Bce?.MCP_USE_ANONYMIZED_TELEMETRY==="false"}getStoredSource(){return typeof localStorage<"u"?localStorage.getItem(Pi("source")):null}static getInstance(){return ra.instance||(ra.instance=new ra),ra.instance}setSource(t){this._source=t,typeof localStorage<"u"&&localStorage.setItem(Pi("source"),t)}getSource(){return this._source}get userId(){if(this._currUserId)return this._currUserId;if(!ME())return this._currUserId=this.UNKNOWN_USER_ID,this._currUserId;try{const t=localStorage.getItem(Pi("user_id"));if(t)this._currUserId=t;else{const n=this.generateUserId();localStorage.setItem(Pi("user_id"),n),this._currUserId=n}this.trackPackageDownload({triggered_by:"user_id_property"}).catch(()=>{})}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}generateUserId(){const t=window.crypto;if(t){const n=new Uint8Array(16);t.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;const r=Array.from(n).map(a=>a.toString(16).padStart(2,"0")).join("");return r.slice(0,8)+"-"+r.slice(8,12)+"-"+r.slice(12,16)+"-"+r.slice(16,20)+"-"+r.slice(20,32)}else return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const r=Math.random()*16|0;return(n==="x"?r:r&3|8).toString(16)})}async capture(t){if(!(!this._posthogClient&&!this._scarfClient)){if(this._posthogClient)try{const n={event:t.name,user_id:this.userId,properties:{...t.properties,mcp_use_version:LE(),language:"typescript",source:this._source,package:"inspector"}};await this._posthogClient.logEvent(n)}catch{}if(this._scarfClient)try{const n={};n.mcp_use_version=LE(),n.user_id=this.userId,n.event=t.name,n.language="typescript",n.source=this._source,n.package="inspector",await this._scarfClient.logEvent(n)}catch{}}}async trackPackageDownload(t){if(this._scarfClient&&ME())try{const n=LE();let r=!1,a=!1;const o=localStorage.getItem(Pi("download_version"));if(o?n>o&&(r=!0,a=!1,localStorage.setItem(Pi("download_version"),n)):(r=!0,a=!0,localStorage.setItem(Pi("download_version"),n)),r){const i={...t||{}};i.mcp_use_version=n,i.user_id=this.userId,i.event="package_download",i.first_download=a,i.language="typescript",i.source=this._source,i.package="inspector",await this._scarfClient.logEvent(i)}}catch{}}async trackInspectorOpen(t){const n=new $ce(t);await this.capture(n)}}const Hce=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Vce=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),wU=e=>{const t=Vce(e);return t.charAt(0).toUpperCase()+t.slice(1)},$H=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),Gce=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var Wce={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Kce=y.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:o,iconNode:i,...l},u)=>y.createElement("svg",{ref:u,...Wce,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:$H("lucide",a),...!o&&!Gce(l)&&{"aria-hidden":"true"},...l},[...i.map(([f,m])=>y.createElement(f,m)),...Array.isArray(o)?o:[o]]));const gt=(e,t)=>{const n=y.forwardRef(({className:r,...a},o)=>y.createElement(Kce,{ref:o,iconNode:t,className:$H(`lucide-${Hce(wU(e))}`,`lucide-${e}`,r),...a}));return n.displayName=wU(e),n};const Yce=[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]],Zce=gt("arrow-down-to-line",Yce);const qce=[["path",{d:"m18 9-6-6-6 6",key:"kcunyi"}],["path",{d:"M12 3v14",key:"7cf3v8"}],["path",{d:"M5 21h14",key:"11awu3"}]],Xce=gt("arrow-up-from-line",qce);const Jce=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Qce=gt("arrow-up",Jce);const eue=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],KN=gt("bell",eue);const tue=[["path",{d:"m11 10 3 3",key:"fzmg1i"}],["path",{d:"M6.5 21A3.5 3.5 0 1 0 3 17.5a2.62 2.62 0 0 1-.708 1.792A1 1 0 0 0 3 21z",key:"p4q2r7"}],["path",{d:"M9.969 17.031 21.378 5.624a1 1 0 0 0-3.002-3.002L6.967 14.031",key:"wy6l02"}]],UH=gt("brush",tue);const nue=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],rue=gt("bug",nue);const aue=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Or=gt("check",aue);const oue=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],hs=gt("chevron-down",oue);const sue=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],tw=gt("chevron-left",sue);const iue=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],zH=gt("chevron-right",iue);const lue=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],cue=gt("chevron-up",lue);const uue=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],due=gt("chevrons-up-down",uue);const fue=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}]],xU=gt("circle-minus",fue);const pue=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],um=gt("clock",pue);const mue=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],YN=gt("code",mue);const hue=[["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["circle",{cx:"12",cy:"12",r:"8",key:"46899m"}]],gue=gt("cog",hue);const bue=[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]],yue=gt("command",bue);const vue=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],wr=gt("copy",vue);const wue=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],nw=gt("database",wue);const xue=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],th=gt("download",xue);const Eue=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],Sue=gt("ellipsis-vertical",Eue);const _ue=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],u_=gt("external-link",_ue);const Tue=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],FH=gt("eye-off",Tue);const Nue=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],d_=gt("eye",Nue);const Cue=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],Rue=gt("file-code",Cue);const kue=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]],Aue=gt("file-image",kue);const Iue=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],ZN=gt("file-text",Iue);const Oue=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],Due=gt("file",Oue);const Lue=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],Mue=gt("folder-open",Lue);const jue=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Pue=gt("globe",jue);const $ue=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],Uue=gt("grip-vertical",$ue);const zue=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],BH=gt("hash",zue);const Fue=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],dm=gt("history",Fue);const Bue=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Up=gt("info",Bue);const Hue=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],HH=gt("key",Hue);const Vue=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],cl=gt("loader-circle",Vue);const Gue=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],qN=gt("maximize-2",Gue);const Wue=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]],fm=gt("maximize",Wue);const Kue=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],Yue=gt("message-circle",Kue);const Zue=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],pm=gt("message-square",Zue);const que=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]],VH=gt("minimize",que);const Xue=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],EU=gt("monitor",Xue);const Jue=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],SU=gt("moon",Jue);const Que=[["path",{d:"M2 10h6V4",key:"zwrco"}],["path",{d:"m2 4 6 6",key:"ug085t"}],["path",{d:"M21 10V7a2 2 0 0 0-2-2h-7",key:"git5jr"}],["path",{d:"M3 14v2a2 2 0 0 0 2 2h3",key:"1f7fh3"}],["rect",{x:"12",y:"14",width:"10",height:"7",rx:"1",key:"1wjs3o"}]],ede=gt("picture-in-picture",Que);const tde=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],GH=gt("play",tde);const nde=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],mm=gt("plus",nde);const rde=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],_U=gt("rotate-ccw",rde);const ade=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],XN=gt("save",ade);const ode=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],sf=gt("search",ode);const sde=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],ide=gt("send",sde);const lde=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],WH=gt("server",lde);const cde=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Xu=gt("settings",cde);const ude=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],dde=gt("shield",ude);const fde=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],pde=gt("sparkles",fde);const mde=[["path",{d:"M21 10.656V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.344",key:"2acyp4"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],KH=gt("square-check-big",mde);const hde=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],gde=gt("square-pen",hde);const bde=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 4h.01",key:"1ujb9j"}],["path",{d:"M20 12h.01",key:"1ykeid"}],["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M4 12h.01",key:"158zrr"}],["path",{d:"M17.657 6.343h.01",key:"31pqzk"}],["path",{d:"M17.657 17.657h.01",key:"jehnf4"}],["path",{d:"M6.343 17.657h.01",key:"gdk6ow"}],["path",{d:"M6.343 6.343h.01",key:"1uurf0"}]],TU=gt("sun-dim",bde);const yde=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],jE=gt("terminal",yde);const vde=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],ni=gt("trash-2",vde);const wde=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],xde=gt("trash",wde);const Ede=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],dc=gt("wrench",Ede);const Sde=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],vs=gt("x",Sde);const _de=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],hm=gt("zap",_de);var YH=e=>{throw TypeError(e)},Tde=(e,t,n)=>t.has(e)||YH("Cannot "+n),PE=(e,t,n)=>(Tde(e,t,"read from private field"),n?n.call(e):t.get(e)),Nde=(e,t,n)=>t.has(e)?YH("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Cde=(e=>(e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE",e))(Cde||{}),NU="popstate";function ZH(e={}){let{initialEntries:t=["/"],initialIndex:n,v5Compat:r=!1}=e,a;a=t.map((b,E)=>m(b,typeof b=="string"?null:b.state,E===0?"default":void 0));let o=u(n??a.length-1),i="POP",l=null;function u(b){return Math.min(Math.max(b,0),a.length-1)}function f(){return a[o]}function m(b,E=null,x){let w=ri(a?f().pathname:"/",b,E,x);return Un(w.pathname.charAt(0)==="/",`relative pathnames are not supported in memory history: ${JSON.stringify(b)}`),w}function h(b){return typeof b=="string"?b:ga(b)}return{get index(){return o},get action(){return i},get location(){return f()},createHref:h,createURL(b){return new URL(h(b),"http://localhost")},encodeLocation(b){let E=typeof b=="string"?Ro(b):b;return{pathname:E.pathname||"",search:E.search||"",hash:E.hash||""}},push(b,E){i="PUSH";let x=m(b,E);o+=1,a.splice(o,a.length,x),r&&l&&l({action:i,location:x,delta:1})},replace(b,E){i="REPLACE";let x=m(b,E);a[o]=x,r&&l&&l({action:i,location:x,delta:0})},go(b){i="POP";let E=u(o+b),x=a[E];o=E,l&&l({action:i,location:x,delta:b})},listen(b){return l=b,()=>{l=null}}}}function qH(e={}){function t(r,a){let{pathname:o,search:i,hash:l}=r.location;return ri("",{pathname:o,search:i,hash:l},a.state&&a.state.usr||null,a.state&&a.state.key||"default")}function n(r,a){return typeof a=="string"?a:ga(a)}return JH(t,n,null,e)}function XH(e={}){function t(a,o){let{pathname:i="/",search:l="",hash:u=""}=Ro(a.location.hash.substring(1));return!i.startsWith("/")&&!i.startsWith(".")&&(i="/"+i),ri("",{pathname:i,search:l,hash:u},o.state&&o.state.usr||null,o.state&&o.state.key||"default")}function n(a,o){let i=a.document.querySelector("base"),l="";if(i&&i.getAttribute("href")){let u=a.location.href,f=u.indexOf("#");l=f===-1?u:u.slice(0,f)}return l+"#"+(typeof o=="string"?o:ga(o))}function r(a,o){Un(a.pathname.charAt(0)==="/",`relative pathnames are not supported in hash history.push(${JSON.stringify(o)})`)}return JH(t,n,r,e)}function Et(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Un(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function Rde(){return Math.random().toString(36).substring(2,10)}function CU(e,t){return{usr:e.state,key:e.key,idx:t}}function ri(e,t,n=null,r){return{pathname:typeof e=="string"?e:e.pathname,search:"",hash:"",...typeof t=="string"?Ro(t):t,state:n,key:t&&t.key||r||Rde()}}function ga({pathname:e="/",search:t="",hash:n=""}){return t&&t!=="?"&&(e+=t.charAt(0)==="?"?t:"?"+t),n&&n!=="#"&&(e+=n.charAt(0)==="#"?n:"#"+n),e}function Ro(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function JH(e,t,n,r={}){let{window:a=document.defaultView,v5Compat:o=!1}=r,i=a.history,l="POP",u=null,f=m();f==null&&(f=0,i.replaceState({...i.state,idx:f},""));function m(){return(i.state||{idx:null}).idx}function h(){l="POP";let w=m(),S=w==null?null:w-f;f=w,u&&u({action:l,location:x.location,delta:S})}function g(w,S){l="PUSH";let _=ri(x.location,w,S);n&&n(_,w),f=m()+1;let T=CU(_,f),k=x.createHref(_);try{i.pushState(T,"",k)}catch(R){if(R instanceof DOMException&&R.name==="DataCloneError")throw R;a.location.assign(k)}o&&u&&u({action:l,location:x.location,delta:1})}function b(w,S){l="REPLACE";let _=ri(x.location,w,S);n&&n(_,w),f=m();let T=CU(_,f),k=x.createHref(_);i.replaceState(T,"",k),o&&u&&u({action:l,location:x.location,delta:0})}function E(w){return QH(w)}let x={get action(){return l},get location(){return e(a,i)},listen(w){if(u)throw new Error("A history only accepts one active listener");return a.addEventListener(NU,h),u=w,()=>{a.removeEventListener(NU,h),u=null}},createHref(w){return t(a,w)},createURL:E,encodeLocation(w){let S=E(w);return{pathname:S.pathname,search:S.search,hash:S.hash}},push:g,replace:b,go(w){return i.go(w)}};return x}function QH(e,t=!1){let n="http://localhost";typeof window<"u"&&(n=window.location.origin!=="null"?window.location.origin:window.location.href),Et(n,"No window.location.(origin|href) available to create URL");let r=typeof e=="string"?e:ga(e);return r=r.replace(/ $/,"%20"),!t&&r.startsWith("//")&&(r=n+r),new URL(r,n)}function zTe(e){return{defaultValue:e}}var Cp,Mu=class{constructor(e){if(Nde(this,Cp,new Map),e)for(let[t,n]of e)this.set(t,n)}get(e){if(PE(this,Cp).has(e))return PE(this,Cp).get(e);if(e.defaultValue!==void 0)return e.defaultValue;throw new Error("No value found for context")}set(e,t){PE(this,Cp).set(e,t)}};Cp=new WeakMap;var kde=new Set(["lazy","caseSensitive","path","id","index","children"]);function Ade(e){return kde.has(e)}var Ide=new Set(["lazy","caseSensitive","path","id","index","middleware","children"]);function Ode(e){return Ide.has(e)}function Dde(e){return e.index===!0}function fc(e,t,n=[],r={},a=!1){return e.map((o,i)=>{let l=[...n,String(i)],u=typeof o.id=="string"?o.id:l.join("-");if(Et(o.index!==!0||!o.children,"Cannot specify children on an index route"),Et(a||!r[u],`Found a route id collision on id "${u}". Route id's must be globally unique within Data Router usages`),Dde(o)){let f={...o,id:u};return r[u]=RU(f,t(f)),f}else{let f={...o,id:u,children:void 0};return r[u]=RU(f,t(f)),o.children&&(f.children=fc(o.children,t,l,r,a)),f}})}function RU(e,t){return Object.assign(e,{...t,...typeof t.lazy=="object"&&t.lazy!=null?{lazy:{...e.lazy,...t.lazy}}:{}})}function Uo(e,t,n="/"){return Rp(e,t,n,!1)}function Rp(e,t,n,r){let a=typeof t=="string"?Ro(t):t,o=Na(a.pathname||"/",n);if(o==null)return null;let i=tV(e);Lde(i);let l=null;for(let u=0;l==null&&u<i.length;++u){let f=aV(o);l=Hde(i[u],f,r)}return l}function eV(e,t){let{route:n,pathname:r,params:a}=e;return{id:n.id,pathname:r,params:a,data:t[n.id],loaderData:t[n.id],handle:n.handle}}function tV(e,t=[],n=[],r="",a=!1){let o=(i,l,u=a,f)=>{let m={relativePath:f===void 0?i.path||"":f,caseSensitive:i.caseSensitive===!0,childrenIndex:l,route:i};if(m.relativePath.startsWith("/")){if(!m.relativePath.startsWith(r)&&u)return;Et(m.relativePath.startsWith(r),`Absolute route path "${m.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),m.relativePath=m.relativePath.slice(r.length)}let h=is([r,m.relativePath]),g=n.concat(m);i.children&&i.children.length>0&&(Et(i.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${h}".`),tV(i.children,t,g,h,u)),!(i.path==null&&!i.index)&&t.push({path:h,score:Fde(h,i.index),routesMeta:g})};return e.forEach((i,l)=>{if(i.path===""||!i.path?.includes("?"))o(i,l);else for(let u of nV(i.path))o(i,l,!0,u)}),t}function nV(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,a=n.endsWith("?"),o=n.replace(/\?$/,"");if(r.length===0)return a?[o,""]:[o];let i=nV(r.join("/")),l=[];return l.push(...i.map(u=>u===""?o:[o,u].join("/"))),a&&l.push(...i),l.map(u=>e.startsWith("/")&&u===""?"/":u)}function Lde(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:Bde(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}var Mde=/^:[\w-]+$/,jde=3,Pde=2,$de=1,Ude=10,zde=-2,kU=e=>e==="*";function Fde(e,t){let n=e.split("/"),r=n.length;return n.some(kU)&&(r+=zde),t&&(r+=Pde),n.filter(a=>!kU(a)).reduce((a,o)=>a+(Mde.test(o)?jde:o===""?$de:Ude),r)}function Bde(e,t){return e.length===t.length&&e.slice(0,-1).every((r,a)=>r===t[a])?e[e.length-1]-t[t.length-1]:0}function Hde(e,t,n=!1){let{routesMeta:r}=e,a={},o="/",i=[];for(let l=0;l<r.length;++l){let u=r[l],f=l===r.length-1,m=o==="/"?t:t.slice(o.length)||"/",h=gm({path:u.relativePath,caseSensitive:u.caseSensitive,end:f},m),g=u.route;if(!h&&f&&n&&!r[r.length-1].route.index&&(h=gm({path:u.relativePath,caseSensitive:u.caseSensitive,end:!1},m)),!h)return null;Object.assign(a,h.params),i.push({params:a,pathname:is([o,h.pathname]),pathnameBase:Wde(is([o,h.pathnameBase])),route:g}),h.pathnameBase!=="/"&&(o=is([o,h.pathnameBase]))}return i}function FTe(e,t={}){let n=e;n.endsWith("*")&&n!=="*"&&!n.endsWith("/*")&&(Un(!1,`Route path "${n}" will be treated as if it were "${n.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${n.replace(/\*$/,"/*")}".`),n=n.replace(/\*$/,"/*"));const r=n.startsWith("/")?"/":"",a=i=>i==null?"":typeof i=="string"?i:String(i),o=n.split(/\/+/).map((i,l,u)=>{if(l===u.length-1&&i==="*")return a(t["*"]);const m=i.match(/^:([\w-]+)(\??)(.*)/);if(m){const[,h,g,b]=m;let E=t[h];return Et(g==="?"||E!=null,`Missing ":${h}" param`),encodeURIComponent(a(E))+b}return i.replace(/\?$/g,"")}).filter(i=>!!i);return r+o.join("/")}function gm(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=rV(e.path,e.caseSensitive,e.end),a=t.match(n);if(!a)return null;let o=a[0],i=o.replace(/(.)\/+$/,"$1"),l=a.slice(1);return{params:r.reduce((f,{paramName:m,isOptional:h},g)=>{if(m==="*"){let E=l[g]||"";i=o.slice(0,o.length-E.length).replace(/(.)\/+$/,"$1")}const b=l[g];return h&&!b?f[m]=void 0:f[m]=(b||"").replace(/%2F/g,"/"),f},{}),pathname:o,pathnameBase:i,pattern:e}}function rV(e,t=!1,n=!0){Un(e==="*"||!e.endsWith("*")||e.endsWith("/*"),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,"/*")}".`);let r=[],a="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(i,l,u)=>(r.push({paramName:l,isOptional:u!=null}),u?"/?([^\\/]+)?":"/([^\\/]+)")).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return e.endsWith("*")?(r.push({paramName:"*"}),a+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?a+="\\/*$":e!==""&&e!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),r]}function aV(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Un(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function Na(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function Vde({basename:e,pathname:t}){return t==="/"?e:is([e,t])}var oV=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,rw=e=>oV.test(e);function Gde(e,t="/"){let{pathname:n,search:r="",hash:a=""}=typeof e=="string"?Ro(e):e,o;if(n)if(rw(n))o=n;else{if(n.includes("//")){let i=n;n=n.replace(/\/\/+/g,"/"),Un(!1,`Pathnames cannot have embedded double slashes - normalizing ${i} -> ${n}`)}n.startsWith("/")?o=AU(n.substring(1),"/"):o=AU(n,t)}else o=t;return{pathname:o,search:Kde(r),hash:Yde(a)}}function AU(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(a=>{a===".."?n.length>1&&n.pop():a!=="."&&n.push(a)}),n.length>1?n.join("/"):"/"}function $E(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function sV(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function aw(e){let t=sV(e);return t.map((n,r)=>r===t.length-1?n.pathname:n.pathnameBase)}function ow(e,t,n,r=!1){let a;typeof e=="string"?a=Ro(e):(a={...e},Et(!a.pathname||!a.pathname.includes("?"),$E("?","pathname","search",a)),Et(!a.pathname||!a.pathname.includes("#"),$E("#","pathname","hash",a)),Et(!a.search||!a.search.includes("#"),$E("#","search","hash",a)));let o=e===""||a.pathname==="",i=o?"/":a.pathname,l;if(i==null)l=n;else{let h=t.length-1;if(!r&&i.startsWith("..")){let g=i.split("/");for(;g[0]==="..";)g.shift(),h-=1;a.pathname=g.join("/")}l=h>=0?t[h]:"/"}let u=Gde(a,l),f=i&&i!=="/"&&i.endsWith("/"),m=(o||i===".")&&n.endsWith("/");return!u.pathname.endsWith("/")&&(f||m)&&(u.pathname+="/"),u}var is=e=>e.join("/").replace(/\/\/+/g,"/"),Wde=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),Kde=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,Yde=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e,Zde=class{constructor(e,t){this.type="DataWithResponseInit",this.data=e,this.init=t||null}};function qde(e,t){return new Zde(e,typeof t=="number"?{status:t}:t)}var JN=(e,t=302)=>{let n=t;typeof n=="number"?n={status:n}:typeof n.status>"u"&&(n.status=302);let r=new Headers(n.headers);return r.set("Location",e),new Response(null,{...n,headers:r})},BTe=(e,t)=>{let n=JN(e,t);return n.headers.set("X-Remix-Reload-Document","true"),n},HTe=(e,t)=>{let n=JN(e,t);return n.headers.set("X-Remix-Replace","true"),n},ws=class{constructor(e,t,n,r=!1){this.status=e,this.statusText=t||"",this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function So(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}function Ys(e){return e.map(t=>t.route.path).filter(Boolean).join("/").replace(/\/\/*/g,"/")||"/"}var iV=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function lV(e,t){let n=e;if(typeof n!="string"||!oV.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,a=!1;if(iV)try{let o=new URL(window.location.href),i=n.startsWith("//")?new URL(o.protocol+n):new URL(n),l=Na(i.pathname,t);i.origin===o.origin&&l!=null?n=l+i.search+i.hash:a=!0}catch{Un(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:a,to:n}}var qi=Symbol("Uninstrumented");function cV(e,t){let n={lazy:[],"lazy.loader":[],"lazy.action":[],"lazy.middleware":[],middleware:[],loader:[],action:[]};e.forEach(a=>a({id:t.id,index:t.index,path:t.path,instrument(o){let i=Object.keys(n);for(let l of i)o[l]&&n[l].push(o[l])}}));let r={};if(typeof t.lazy=="function"&&n.lazy.length>0){let a=Ql(n.lazy,t.lazy,()=>{});a&&(r.lazy=a)}if(typeof t.lazy=="object"){let a=t.lazy;["middleware","loader","action"].forEach(o=>{let i=a[o],l=n[`lazy.${o}`];if(typeof i=="function"&&l.length>0){let u=Ql(l,i,()=>{});u&&(r.lazy=Object.assign(r.lazy||{},{[o]:u}))}})}return["loader","action"].forEach(a=>{let o=t[a];if(typeof o=="function"&&n[a].length>0){let i=o[qi]??o,l=Ql(n[a],i,(...u)=>IU(u[0]));l&&(a==="loader"&&i.hydrate===!0&&(l.hydrate=!0),l[qi]=i,r[a]=l)}}),t.middleware&&t.middleware.length>0&&n.middleware.length>0&&(r.middleware=t.middleware.map(a=>{let o=a[qi]??a,i=Ql(n.middleware,o,(...l)=>IU(l[0]));return i?(i[qi]=o,i):a})),r}function Xde(e,t){let n={navigate:[],fetch:[]};if(t.forEach(r=>r({instrument(a){let o=Object.keys(a);for(let i of o)a[i]&&n[i].push(a[i])}})),n.navigate.length>0){let r=e.navigate[qi]??e.navigate,a=Ql(n.navigate,r,(...o)=>{let[i,l]=o;return{to:typeof i=="number"||typeof i=="string"?i:i?ga(i):".",...OU(e,l??{})}});a&&(a[qi]=r,e.navigate=a)}if(n.fetch.length>0){let r=e.fetch[qi]??e.fetch,a=Ql(n.fetch,r,(...o)=>{let[i,,l,u]=o;return{href:l??".",fetcherKey:i,...OU(e,u??{})}});a&&(a[qi]=r,e.fetch=a)}return e}function VTe(e,t){let n={request:[]};t.forEach(a=>a({instrument(o){let i=Object.keys(o);for(let l of i)o[l]&&n[l].push(o[l])}}));let r=e;return n.request.length>0&&(r=Ql(n.request,e,(...a)=>{let[o,i]=a;return{request:dV(o),context:i!=null?fV(i):i}})),r}function Ql(e,t,n){return e.length===0?null:async(...r)=>{let a=await uV(e,n(...r),()=>t(...r),e.length-1);if(a.type==="error")throw a.value;return a.value}}async function uV(e,t,n,r){let a=e[r],o;if(a){let i,l=async()=>(i?console.error("You cannot call instrumented handlers more than once"):i=uV(e,t,n,r-1),o=await i,Et(o,"Expected a result"),o.type==="error"&&o.value instanceof Error?{status:"error",error:o.value}:{status:"success",error:void 0});try{await a(l,t)}catch(u){console.error("An instrumentation function threw an error:",u)}i||await l(),await i}else try{o={type:"success",value:await n()}}catch(i){o={type:"error",value:i}}return o||{type:"error",value:new Error("No result assigned in instrumentation chain.")}}function IU(e){let{request:t,context:n,params:r,unstable_pattern:a}=e;return{request:dV(t),params:{...r},unstable_pattern:a,context:fV(n)}}function OU(e,t){return{currentUrl:ga(e.state.location),..."formMethod"in t?{formMethod:t.formMethod}:{},..."formEncType"in t?{formEncType:t.formEncType}:{},..."formData"in t?{formData:t.formData}:{},..."body"in t?{body:t.body}:{}}}function dV(e){return{method:e.method,url:e.url,headers:{get:(...t)=>e.headers.get(...t)}}}function fV(e){if(Qde(e)){let t={...e};return Object.freeze(t),t}else return{get:t=>e.get(t)}}var Jde=Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function Qde(e){if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null||Object.getOwnPropertyNames(t).sort().join("\0")===Jde}var pV=["POST","PUT","PATCH","DELETE"],efe=new Set(pV),tfe=["GET",...pV],nfe=new Set(tfe),mV=new Set([301,302,303,307,308]),rfe=new Set([307,308]),oy={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},QN={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},ql={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},hV=e=>({hasErrorBoundary:!!e.hasErrorBoundary}),gV="remix-router-transitions",bV=Symbol("ResetLoaderData");function eC(e){const t=e.window?e.window:typeof window<"u"?window:void 0,n=typeof t<"u"&&typeof t.document<"u"&&typeof t.document.createElement<"u";Et(e.routes.length>0,"You must provide a non-empty routes array to createRouter");let r=e.hydrationRouteProperties||[],a=e.mapRouteProperties||hV,o=a;if(e.unstable_instrumentations){let oe=e.unstable_instrumentations;o=ce=>({...a(ce),...cV(oe.map(ye=>ye.route).filter(Boolean),ce)})}let i={},l=fc(e.routes,o,void 0,i),u,f=e.basename||"/";f.startsWith("/")||(f=`/${f}`);let m=e.dataStrategy||dfe,h={...e.future},g=null,b=new Set,E=null,x=null,w=null,S=e.hydrationData!=null,_=Uo(l,e.history.location,f),T=!1,k=null,R;if(_==null&&!e.patchRoutesOnNavigation){let oe=Ar(404,{pathname:e.history.location.pathname}),{matches:ce,route:ye}=ju(l);R=!0,_=ce,k={[ye.id]:oe}}else if(_&&!e.hydrationData&&zt(_,l,e.history.location.pathname).active&&(_=null),_)if(_.some(oe=>oe.route.lazy))R=!1;else if(!_.some(oe=>tC(oe.route)))R=!0;else{let oe=e.hydrationData?e.hydrationData.loaderData:null,ce=e.hydrationData?e.hydrationData.errors:null;if(ce){let ye=_.findIndex(ke=>ce[ke.route.id]!==void 0);R=_.slice(0,ye+1).every(ke=>!p_(ke.route,oe,ce))}else R=_.every(ye=>!p_(ye.route,oe,ce))}else{R=!1,_=[];let oe=zt(null,l,e.history.location.pathname);oe.active&&oe.matches&&(T=!0,_=oe.matches)}let A,C={historyAction:e.history.action,location:e.history.location,matches:_,initialized:R,navigation:oy,restoreScrollPosition:e.hydrationData!=null?!1:null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||k,fetchers:new Map,blockers:new Map},O="POP",M=null,L=!1,j,B=!1,K=new Map,Z=null,te=!1,V=!1,Y=new Set,F=new Map,ae=0,ee=-1,P=new Map,H=new Set,U=new Map,D=new Map,$=new Set,G=new Map,W,re=null;function pe(){if(g=e.history.listen(({action:oe,location:ce,delta:ye})=>{if(W){W(),W=void 0;return}Un(G.size===0||ye!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let ke=Pt({currentLocation:C.location,nextLocation:ce,historyAction:oe});if(ke&&ye!=null){let ge=new Promise(_e=>{W=_e});e.history.go(ye*-1),jt(ke,{state:"blocked",location:ce,proceed(){jt(ke,{state:"proceeding",proceed:void 0,reset:void 0,location:ce}),ge.then(()=>e.history.go(ye))},reset(){let _e=new Map(C.blockers);_e.set(ke,ql),J({blockers:_e})}}),M?.resolve(),M=null;return}return Te(oe,ce)}),n){yfe(t,K);let oe=()=>vfe(t,K);t.addEventListener("pagehide",oe),Z=()=>t.removeEventListener("pagehide",oe)}return C.initialized||Te("POP",C.location,{initialHydration:!0}),A}function me(){g&&g(),Z&&Z(),b.clear(),j&&j.abort(),C.fetchers.forEach((oe,ce)=>ot(ce)),C.blockers.forEach((oe,ce)=>Nt(ce))}function ne(oe){return b.add(oe),()=>b.delete(oe)}function J(oe,ce={}){oe.matches&&(oe.matches=oe.matches.map(ge=>{let _e=i[ge.route.id],Ne=ge.route;return Ne.element!==_e.element||Ne.errorElement!==_e.errorElement||Ne.hydrateFallbackElement!==_e.hydrateFallbackElement?{...ge,route:_e}:ge})),C={...C,...oe};let ye=[],ke=[];C.fetchers.forEach((ge,_e)=>{ge.state==="idle"&&($.has(_e)?ye.push(_e):ke.push(_e))}),$.forEach(ge=>{!C.fetchers.has(ge)&&!F.has(ge)&&ye.push(ge)}),[...b].forEach(ge=>ge(C,{deletedFetchers:ye,newErrors:oe.errors??null,viewTransitionOpts:ce.viewTransitionOpts,flushSync:ce.flushSync===!0})),ye.forEach(ge=>ot(ge)),ke.forEach(ge=>C.fetchers.delete(ge))}function X(oe,ce,{flushSync:ye}={}){let ke=C.actionData!=null&&C.navigation.formMethod!=null&&Zr(C.navigation.formMethod)&&C.navigation.state==="loading"&&oe.state?._isRedirect!==!0,ge;ce.actionData?Object.keys(ce.actionData).length>0?ge=ce.actionData:ge=null:ke?ge=C.actionData:ge=null;let _e=ce.loaderData?VU(C.loaderData,ce.loaderData,ce.matches||[],ce.errors):C.loaderData,Ne=C.blockers;Ne.size>0&&(Ne=new Map(Ne),Ne.forEach((qe,et)=>Ne.set(et,ql)));let Ae=te?!1:Ht(oe,ce.matches||C.matches),Pe=L===!0||C.navigation.formMethod!=null&&Zr(C.navigation.formMethod)&&oe.state?._isRedirect!==!0;u&&(l=u,u=void 0),te||O==="POP"||(O==="PUSH"?e.history.push(oe,oe.state):O==="REPLACE"&&e.history.replace(oe,oe.state));let Ze;if(O==="POP"){let qe=K.get(C.location.pathname);qe&&qe.has(oe.pathname)?Ze={currentLocation:C.location,nextLocation:oe}:K.has(oe.pathname)&&(Ze={currentLocation:oe,nextLocation:C.location})}else if(B){let qe=K.get(C.location.pathname);qe?qe.add(oe.pathname):(qe=new Set([oe.pathname]),K.set(C.location.pathname,qe)),Ze={currentLocation:C.location,nextLocation:oe}}J({...ce,actionData:ge,loaderData:_e,historyAction:O,location:oe,initialized:!0,navigation:oy,revalidation:"idle",restoreScrollPosition:Ae,preventScrollReset:Pe,blockers:Ne},{viewTransitionOpts:Ze,flushSync:ye===!0}),O="POP",L=!1,B=!1,te=!1,V=!1,M?.resolve(),M=null,re?.resolve(),re=null}async function se(oe,ce){if(M?.resolve(),M=null,typeof oe=="number"){M||(M=KU());let tt=M.promise;return e.history.go(oe),tt}let ye=f_(C.location,C.matches,f,oe,ce?.fromRouteId,ce?.relative),{path:ke,submission:ge,error:_e}=LU(!1,ye,ce),Ne=C.location,Ae=ri(C.location,ke,ce&&ce.state);Ae={...Ae,...e.history.encodeLocation(Ae)};let Pe=ce&&ce.replace!=null?ce.replace:void 0,Ze="PUSH";Pe===!0?Ze="REPLACE":Pe===!1||ge!=null&&Zr(ge.formMethod)&&ge.formAction===C.location.pathname+C.location.search&&(Ze="REPLACE");let qe=ce&&"preventScrollReset"in ce?ce.preventScrollReset===!0:void 0,et=(ce&&ce.flushSync)===!0,Ut=Pt({currentLocation:Ne,nextLocation:Ae,historyAction:Ze});if(Ut){jt(Ut,{state:"blocked",location:Ae,proceed(){jt(Ut,{state:"proceeding",proceed:void 0,reset:void 0,location:Ae}),se(oe,ce)},reset(){let tt=new Map(C.blockers);tt.set(Ut,ql),J({blockers:tt})}});return}await Te(Ze,Ae,{submission:ge,pendingError:_e,preventScrollReset:qe,replace:ce&&ce.replace,enableViewTransition:ce&&ce.viewTransition,flushSync:et,callSiteDefaultShouldRevalidate:ce&&ce.unstable_defaultShouldRevalidate})}function he(){re||(re=KU()),st(),J({revalidation:"loading"});let oe=re.promise;return C.navigation.state==="submitting"?oe:C.navigation.state==="idle"?(Te(C.historyAction,C.location,{startUninterruptedRevalidation:!0}),oe):(Te(O||C.historyAction,C.navigation.location,{overrideNavigation:C.navigation,enableViewTransition:B===!0}),oe)}async function Te(oe,ce,ye){j&&j.abort(),j=null,O=oe,te=(ye&&ye.startUninterruptedRevalidation)===!0,$t(C.location,C.matches),L=(ye&&ye.preventScrollReset)===!0,B=(ye&&ye.enableViewTransition)===!0;let ke=u||l,ge=ye&&ye.overrideNavigation,_e=ye?.initialHydration&&C.matches&&C.matches.length>0&&!T?C.matches:Uo(ke,ce,f),Ne=(ye&&ye.flushSync)===!0;if(_e&&C.initialized&&!V&&pfe(C.location,ce)&&!(ye&&ye.submission&&Zr(ye.submission.formMethod))){X(ce,{matches:_e},{flushSync:Ne});return}let Ae=zt(_e,ke,ce.pathname);if(Ae.active&&Ae.matches&&(_e=Ae.matches),!_e){let{error:Ct,notFoundMatches:Qe,route:Ke}=Xt(ce.pathname);X(ce,{matches:Qe,loaderData:{},errors:{[Ke.id]:Ct}},{flushSync:Ne});return}j=new AbortController;let Pe=Su(e.history,ce,j.signal,ye&&ye.submission),Ze=e.getContext?await e.getContext():new Mu,qe;if(ye&&ye.pendingError)qe=[wo(_e).route.id,{type:"error",error:ye.pendingError}];else if(ye&&ye.submission&&Zr(ye.submission.formMethod)){let Ct=await Be(Pe,ce,ye.submission,_e,Ze,Ae.active,ye&&ye.initialHydration===!0,{replace:ye.replace,flushSync:Ne});if(Ct.shortCircuited)return;if(Ct.pendingActionResult){let[Qe,Ke]=Ct.pendingActionResult;if(zr(Ke)&&So(Ke.error)&&Ke.error.status===404){j=null,X(ce,{matches:Ct.matches,loaderData:{},errors:{[Qe]:Ke.error}});return}}_e=Ct.matches||_e,qe=Ct.pendingActionResult,ge=UE(ce,ye.submission),Ne=!1,Ae.active=!1,Pe=Su(e.history,Pe.url,Pe.signal)}let{shortCircuited:et,matches:Ut,loaderData:tt,errors:xt}=await $e(Pe,ce,_e,Ze,Ae.active,ge,ye&&ye.submission,ye&&ye.fetcherSubmission,ye&&ye.replace,ye&&ye.initialHydration===!0,Ne,qe,ye&&ye.callSiteDefaultShouldRevalidate);et||(j=null,X(ce,{matches:Ut||_e,...GU(qe),loaderData:tt,errors:xt}))}async function Be(oe,ce,ye,ke,ge,_e,Ne,Ae={}){st();let Pe=gfe(ce,ye);if(J({navigation:Pe},{flushSync:Ae.flushSync===!0}),_e){let et=await Ln(ke,ce.pathname,oe.signal);if(et.type==="aborted")return{shortCircuited:!0};if(et.type==="error"){if(et.partialMatches.length===0){let{matches:tt,route:xt}=ju(l);return{matches:tt,pendingActionResult:[xt.id,{type:"error",error:et.error}]}}let Ut=wo(et.partialMatches).route.id;return{matches:et.partialMatches,pendingActionResult:[Ut,{type:"error",error:et.error}]}}else if(et.matches)ke=et.matches;else{let{notFoundMatches:Ut,error:tt,route:xt}=Xt(ce.pathname);return{matches:Ut,pendingActionResult:[xt.id,{type:"error",error:tt}]}}}let Ze,qe=Ju(ke,ce);if(!qe.route.action&&!qe.route.lazy)Ze={type:"error",error:Ar(405,{method:oe.method,pathname:ce.pathname,routeId:qe.route.id})};else{let et=el(o,i,oe,ke,qe,Ne?[]:r,ge),Ut=await Ce(oe,et,ge,null);if(Ze=Ut[qe.route.id],!Ze){for(let tt of ke)if(Ut[tt.route.id]){Ze=Ut[tt.route.id];break}}if(oe.signal.aborted)return{shortCircuited:!0}}if(Xi(Ze)){let et;return Ae&&Ae.replace!=null?et=Ae.replace:et=FU(Ze.response.headers.get("Location"),new URL(oe.url),f,e.history)===C.location.pathname+C.location.search,await Ee(oe,Ze,!0,{submission:ye,replace:et}),{shortCircuited:!0}}if(zr(Ze)){let et=wo(ke,qe.route.id);return(Ae&&Ae.replace)!==!0&&(O="PUSH"),{matches:ke,pendingActionResult:[et.route.id,Ze,qe.route.id]}}return{matches:ke,pendingActionResult:[qe.route.id,Ze]}}async function $e(oe,ce,ye,ke,ge,_e,Ne,Ae,Pe,Ze,qe,et,Ut){let tt=_e||UE(ce,Ne),xt=Ne||Ae||WU(tt),Ct=!te&&!Ze;if(ge){if(Ct){let Rt=Ge(et);J({navigation:tt,...Rt!==void 0?{actionData:Rt}:{}},{flushSync:qe})}let Ft=await Ln(ye,ce.pathname,oe.signal);if(Ft.type==="aborted")return{shortCircuited:!0};if(Ft.type==="error"){if(Ft.partialMatches.length===0){let{matches:xr,route:Wn}=ju(l);return{matches:xr,loaderData:{},errors:{[Wn.id]:Ft.error}}}let Rt=wo(Ft.partialMatches).route.id;return{matches:Ft.partialMatches,loaderData:{},errors:{[Rt]:Ft.error}}}else if(Ft.matches)ye=Ft.matches;else{let{error:Rt,notFoundMatches:xr,route:Wn}=Xt(ce.pathname);return{matches:xr,loaderData:{},errors:{[Wn.id]:Rt}}}}let Qe=u||l,{dsMatches:Ke,revalidatingFetchers:St}=MU(oe,ke,o,i,e.history,C,ye,xt,ce,Ze?[]:r,Ze===!0,V,Y,$,U,H,Qe,f,e.patchRoutesOnNavigation!=null,et,Ut);if(ee=++ae,!e.dataStrategy&&!Ke.some(Ft=>Ft.shouldLoad)&&!Ke.some(Ft=>Ft.route.middleware&&Ft.route.middleware.length>0)&&St.length===0){let Ft=We();return X(ce,{matches:ye,loaderData:{},errors:et&&zr(et[1])?{[et[0]]:et[1].error}:null,...GU(et),...Ft?{fetchers:new Map(C.fetchers)}:{}},{flushSync:qe}),{shortCircuited:!0}}if(Ct){let Ft={};if(!ge){Ft.navigation=tt;let Rt=Ge(et);Rt!==void 0&&(Ft.actionData=Rt)}St.length>0&&(Ft.fetchers=dt(St)),J(Ft,{flushSync:qe})}St.forEach(Ft=>{qt(Ft.key),Ft.controller&&F.set(Ft.key,Ft.controller)});let En=()=>St.forEach(Ft=>qt(Ft.key));j&&j.signal.addEventListener("abort",En);let{loaderResults:ht,fetcherResults:Fn}=await He(Ke,St,oe,ke);if(oe.signal.aborted)return{shortCircuited:!0};j&&j.signal.removeEventListener("abort",En),St.forEach(Ft=>F.delete(Ft.key));let _t=Ab(ht);if(_t)return await Ee(oe,_t.result,!0,{replace:Pe}),{shortCircuited:!0};if(_t=Ab(Fn),_t)return H.add(_t.key),await Ee(oe,_t.result,!0,{replace:Pe}),{shortCircuited:!0};let{loaderData:Cn,errors:en}=HU(C,ye,ht,et,St,Fn);Ze&&C.errors&&(en={...C.errors,...en});let bn=We(),Xn=ue(ee),cr=bn||Xn||St.length>0;return{matches:ye,loaderData:Cn,errors:en,...cr?{fetchers:new Map(C.fetchers)}:{}}}function Ge(oe){if(oe&&!zr(oe[1]))return{[oe[0]]:oe[1].data};if(C.actionData)return Object.keys(C.actionData).length===0?null:C.actionData}function dt(oe){return oe.forEach(ce=>{let ye=C.fetchers.get(ce.key),ke=bp(void 0,ye?ye.data:void 0);C.fetchers.set(ce.key,ke)}),new Map(C.fetchers)}async function Ve(oe,ce,ye,ke){qt(oe);let ge=(ke&&ke.flushSync)===!0,_e=u||l,Ne=f_(C.location,C.matches,f,ye,ce,ke?.relative),Ae=Uo(_e,Ne,f),Pe=zt(Ae,_e,Ne);if(Pe.active&&Pe.matches&&(Ae=Pe.matches),!Ae){it(oe,ce,Ar(404,{pathname:Ne}),{flushSync:ge});return}let{path:Ze,submission:qe,error:et}=LU(!0,Ne,ke);if(et){it(oe,ce,et,{flushSync:ge});return}let Ut=e.getContext?await e.getContext():new Mu,tt=(ke&&ke.preventScrollReset)===!0;if(qe&&Zr(qe.formMethod)){await ct(oe,ce,Ze,Ae,Ut,Pe.active,ge,tt,qe,ke&&ke.unstable_defaultShouldRevalidate);return}U.set(oe,{routeId:ce,path:Ze}),await rt(oe,ce,Ze,Ae,Ut,Pe.active,ge,tt,qe)}async function ct(oe,ce,ye,ke,ge,_e,Ne,Ae,Pe,Ze){st(),U.delete(oe);let qe=C.fetchers.get(oe);Je(oe,bfe(Pe,qe),{flushSync:Ne});let et=new AbortController,Ut=Su(e.history,ye,et.signal,Pe);if(_e){let nn=await Ln(ke,new URL(Ut.url).pathname,Ut.signal,oe);if(nn.type==="aborted")return;if(nn.type==="error"){it(oe,ce,nn.error,{flushSync:Ne});return}else if(nn.matches)ke=nn.matches;else{it(oe,ce,Ar(404,{pathname:ye}),{flushSync:Ne});return}}let tt=Ju(ke,ye);if(!tt.route.action&&!tt.route.lazy){let nn=Ar(405,{method:Pe.formMethod,pathname:ye,routeId:ce});it(oe,ce,nn,{flushSync:Ne});return}F.set(oe,et);let xt=ae,Ct=el(o,i,Ut,ke,tt,r,ge),Qe=await Ce(Ut,Ct,ge,oe),Ke=Qe[tt.route.id];if(!Ke){for(let nn of Ct)if(Qe[nn.route.id]){Ke=Qe[nn.route.id];break}}if(Ut.signal.aborted){F.get(oe)===et&&F.delete(oe);return}if($.has(oe)){if(Xi(Ke)||zr(Ke)){Je(oe,Gs(void 0));return}}else{if(Xi(Ke))if(F.delete(oe),ee>xt){Je(oe,Gs(void 0));return}else return H.add(oe),Je(oe,bp(Pe)),Ee(Ut,Ke,!1,{fetcherSubmission:Pe,preventScrollReset:Ae});if(zr(Ke)){it(oe,ce,Ke.error);return}}let St=C.navigation.location||C.location,En=Su(e.history,St,et.signal),ht=u||l,Fn=C.navigation.state!=="idle"?Uo(ht,C.navigation.location,f):C.matches;Et(Fn,"Didn't find any matches after fetcher action");let _t=++ae;P.set(oe,_t);let Cn=bp(Pe,Ke.data);C.fetchers.set(oe,Cn);let{dsMatches:en,revalidatingFetchers:bn}=MU(En,ge,o,i,e.history,C,Fn,Pe,St,r,!1,V,Y,$,U,H,ht,f,e.patchRoutesOnNavigation!=null,[tt.route.id,Ke],Ze);bn.filter(nn=>nn.key!==oe).forEach(nn=>{let va=nn.key,Oc=C.fetchers.get(va),ui=bp(void 0,Oc?Oc.data:void 0);C.fetchers.set(va,ui),qt(va),nn.controller&&F.set(va,nn.controller)}),J({fetchers:new Map(C.fetchers)});let Xn=()=>bn.forEach(nn=>qt(nn.key));et.signal.addEventListener("abort",Xn);let{loaderResults:cr,fetcherResults:Ft}=await He(en,bn,En,ge);if(et.signal.aborted)return;if(et.signal.removeEventListener("abort",Xn),P.delete(oe),F.delete(oe),bn.forEach(nn=>F.delete(nn.key)),C.fetchers.has(oe)){let nn=Gs(Ke.data);C.fetchers.set(oe,nn)}let Rt=Ab(cr);if(Rt)return Ee(En,Rt.result,!1,{preventScrollReset:Ae});if(Rt=Ab(Ft),Rt)return H.add(Rt.key),Ee(En,Rt.result,!1,{preventScrollReset:Ae});let{loaderData:xr,errors:Wn}=HU(C,Fn,cr,void 0,bn,Ft);ue(_t),C.navigation.state==="loading"&&_t>ee?(Et(O,"Expected pending action"),j&&j.abort(),X(C.navigation.location,{matches:Fn,loaderData:xr,errors:Wn,fetchers:new Map(C.fetchers)})):(J({errors:Wn,loaderData:VU(C.loaderData,xr,Fn,Wn),fetchers:new Map(C.fetchers)}),V=!1)}async function rt(oe,ce,ye,ke,ge,_e,Ne,Ae,Pe){let Ze=C.fetchers.get(oe);Je(oe,bp(Pe,Ze?Ze.data:void 0),{flushSync:Ne});let qe=new AbortController,et=Su(e.history,ye,qe.signal);if(_e){let Ke=await Ln(ke,new URL(et.url).pathname,et.signal,oe);if(Ke.type==="aborted")return;if(Ke.type==="error"){it(oe,ce,Ke.error,{flushSync:Ne});return}else if(Ke.matches)ke=Ke.matches;else{it(oe,ce,Ar(404,{pathname:ye}),{flushSync:Ne});return}}let Ut=Ju(ke,ye);F.set(oe,qe);let tt=ae,xt=el(o,i,et,ke,Ut,r,ge),Qe=(await Ce(et,xt,ge,oe))[Ut.route.id];if(F.get(oe)===qe&&F.delete(oe),!et.signal.aborted){if($.has(oe)){Je(oe,Gs(void 0));return}if(Xi(Qe))if(ee>tt){Je(oe,Gs(void 0));return}else{H.add(oe),await Ee(et,Qe,!1,{preventScrollReset:Ae});return}if(zr(Qe)){it(oe,ce,Qe.error);return}Je(oe,Gs(Qe.data))}}async function Ee(oe,ce,ye,{submission:ke,fetcherSubmission:ge,preventScrollReset:_e,replace:Ne}={}){ye||(M?.resolve(),M=null),ce.response.headers.has("X-Remix-Revalidate")&&(V=!0);let Ae=ce.response.headers.get("Location");Et(Ae,"Expected a Location header on the redirect Response"),Ae=FU(Ae,new URL(oe.url),f,e.history);let Pe=ri(C.location,Ae,{_isRedirect:!0});if(n){let xt=!1;if(ce.response.headers.has("X-Remix-Reload-Document"))xt=!0;else if(rw(Ae)){const Ct=QH(Ae,!0);xt=Ct.origin!==t.location.origin||Na(Ct.pathname,f)==null}if(xt){Ne?t.location.replace(Ae):t.location.assign(Ae);return}}j=null;let Ze=Ne===!0||ce.response.headers.has("X-Remix-Replace")?"REPLACE":"PUSH",{formMethod:qe,formAction:et,formEncType:Ut}=C.navigation;!ke&&!ge&&qe&&et&&Ut&&(ke=WU(C.navigation));let tt=ke||ge;if(rfe.has(ce.response.status)&&tt&&Zr(tt.formMethod))await Te(Ze,Pe,{submission:{...tt,formAction:Ae},preventScrollReset:_e||L,enableViewTransition:ye?B:void 0});else{let xt=UE(Pe,ke);await Te(Ze,Pe,{overrideNavigation:xt,fetcherSubmission:ge,preventScrollReset:_e||L,enableViewTransition:ye?B:void 0})}}async function Ce(oe,ce,ye,ke){let ge,_e={};try{ge=await SV(m,oe,ce,ke,ye,!1)}catch(Ne){return ce.filter(Ae=>Ae.shouldLoad).forEach(Ae=>{_e[Ae.route.id]={type:"error",error:Ne}}),_e}if(oe.signal.aborted)return _e;if(!Zr(oe.method))for(let Ne of ce){if(ge[Ne.route.id]?.type==="error")break;!ge.hasOwnProperty(Ne.route.id)&&!C.loaderData.hasOwnProperty(Ne.route.id)&&(!C.errors||!C.errors.hasOwnProperty(Ne.route.id))&&Ne.shouldCallHandler()&&(ge[Ne.route.id]={type:"error",result:new Error(`No result returned from dataStrategy for route ${Ne.route.id}`)})}for(let[Ne,Ae]of Object.entries(ge))if(IV(Ae)){let Pe=Ae.result;_e[Ne]={type:"redirect",response:NV(Pe,oe,Ne,ce,f)}}else _e[Ne]=await TV(Ae);return _e}async function He(oe,ce,ye,ke){let ge=Ce(ye,oe,ke,null),_e=Promise.all(ce.map(async Pe=>{if(Pe.matches&&Pe.match&&Pe.request&&Pe.controller){let qe=(await Ce(Pe.request,Pe.matches,ke,Pe.key))[Pe.match.route.id];return{[Pe.key]:qe}}else return Promise.resolve({[Pe.key]:{type:"error",error:Ar(404,{pathname:Pe.path})}})})),Ne=await ge,Ae=(await _e).reduce((Pe,Ze)=>Object.assign(Pe,Ze),{});return{loaderResults:Ne,fetcherResults:Ae}}function st(){V=!0,U.forEach((oe,ce)=>{F.has(ce)&&Y.add(ce),qt(ce)})}function Je(oe,ce,ye={}){C.fetchers.set(oe,ce),J({fetchers:new Map(C.fetchers)},{flushSync:(ye&&ye.flushSync)===!0})}function it(oe,ce,ye,ke={}){let ge=wo(C.matches,ce);ot(oe),J({errors:{[ge.route.id]:ye},fetchers:new Map(C.fetchers)},{flushSync:(ke&&ke.flushSync)===!0})}function kt(oe){return D.set(oe,(D.get(oe)||0)+1),$.has(oe)&&$.delete(oe),C.fetchers.get(oe)||QN}function Nn(oe,ce){qt(oe,ce?.reason),Je(oe,Gs(null))}function ot(oe){let ce=C.fetchers.get(oe);F.has(oe)&&!(ce&&ce.state==="loading"&&P.has(oe))&&qt(oe),U.delete(oe),P.delete(oe),H.delete(oe),$.delete(oe),Y.delete(oe),C.fetchers.delete(oe)}function zn(oe){let ce=(D.get(oe)||0)-1;ce<=0?(D.delete(oe),$.add(oe)):D.set(oe,ce),J({fetchers:new Map(C.fetchers)})}function qt(oe,ce){let ye=F.get(oe);ye&&(ye.abort(ce),F.delete(oe))}function Ye(oe){for(let ce of oe){let ye=kt(ce),ke=Gs(ye.data);C.fetchers.set(ce,ke)}}function We(){let oe=[],ce=!1;for(let ye of H){let ke=C.fetchers.get(ye);Et(ke,`Expected fetcher: ${ye}`),ke.state==="loading"&&(H.delete(ye),oe.push(ye),ce=!0)}return Ye(oe),ce}function ue(oe){let ce=[];for(let[ye,ke]of P)if(ke<oe){let ge=C.fetchers.get(ye);Et(ge,`Expected fetcher: ${ye}`),ge.state==="loading"&&(qt(ye),P.delete(ye),ce.push(ye))}return Ye(ce),ce.length>0}function It(oe,ce){let ye=C.blockers.get(oe)||ql;return G.get(oe)!==ce&&G.set(oe,ce),ye}function Nt(oe){C.blockers.delete(oe),G.delete(oe)}function jt(oe,ce){let ye=C.blockers.get(oe)||ql;Et(ye.state==="unblocked"&&ce.state==="blocked"||ye.state==="blocked"&&ce.state==="blocked"||ye.state==="blocked"&&ce.state==="proceeding"||ye.state==="blocked"&&ce.state==="unblocked"||ye.state==="proceeding"&&ce.state==="unblocked",`Invalid blocker state transition: ${ye.state} -> ${ce.state}`);let ke=new Map(C.blockers);ke.set(oe,ce),J({blockers:ke})}function Pt({currentLocation:oe,nextLocation:ce,historyAction:ye}){if(G.size===0)return;G.size>1&&Un(!1,"A router only supports one blocker at a time");let ke=Array.from(G.entries()),[ge,_e]=ke[ke.length-1],Ne=C.blockers.get(ge);if(!(Ne&&Ne.state==="proceeding")&&_e({currentLocation:oe,nextLocation:ce,historyAction:ye}))return ge}function Xt(oe){let ce=Ar(404,{pathname:oe}),ye=u||l,{matches:ke,route:ge}=ju(ye);return{notFoundMatches:ke,route:ge,error:ce}}function xn(oe,ce,ye){if(E=oe,w=ce,x=ye||null,!S&&C.navigation===oy){S=!0;let ke=Ht(C.location,C.matches);ke!=null&&J({restoreScrollPosition:ke})}return()=>{E=null,w=null,x=null}}function ut(oe,ce){return x&&x(oe,ce.map(ke=>eV(ke,C.loaderData)))||oe.key}function $t(oe,ce){if(E&&w){let ye=ut(oe,ce);E[ye]=w()}}function Ht(oe,ce){if(E){let ye=ut(oe,ce),ke=E[ye];if(typeof ke=="number")return ke}return null}function zt(oe,ce,ye){if(e.patchRoutesOnNavigation)if(oe){if(Object.keys(oe[0].params).length>0)return{active:!0,matches:Rp(ce,ye,f,!0)}}else return{active:!0,matches:Rp(ce,ye,f,!0)||[]};return{active:!1,matches:null}}async function Ln(oe,ce,ye,ke){if(!e.patchRoutesOnNavigation)return{type:"success",matches:oe};let ge=oe;for(;;){let _e=u==null,Ne=u||l,Ae=i;try{await e.patchRoutesOnNavigation({signal:ye,path:ce,matches:ge,fetcherKey:ke,patch:(qe,et)=>{ye.aborted||jU(qe,et,Ne,Ae,o,!1)}})}catch(qe){return{type:"error",error:qe,partialMatches:ge}}finally{_e&&!ye.aborted&&(l=[...l])}if(ye.aborted)return{type:"aborted"};let Pe=Uo(Ne,ce,f),Ze=null;if(Pe){if(Object.keys(Pe[0].params).length===0)return{type:"success",matches:Pe};if(Ze=Rp(Ne,ce,f,!0),!(Ze&&ge.length<Ze.length&&sn(ge,Ze.slice(0,ge.length))))return{type:"success",matches:Pe}}if(Ze||(Ze=Rp(Ne,ce,f,!0)),!Ze||sn(ge,Ze))return{type:"success",matches:null};ge=Ze}}function sn(oe,ce){return oe.length===ce.length&&oe.every((ye,ke)=>ye.route.id===ce[ke].route.id)}function Mn(oe){i={},u=fc(oe,o,void 0,i)}function qn(oe,ce,ye=!1){let ke=u==null;jU(oe,ce,u||l,i,o,ye),ke&&(l=[...l],J({}))}return A={get basename(){return f},get future(){return h},get state(){return C},get routes(){return l},get window(){return t},initialize:pe,subscribe:ne,enableScrollRestoration:xn,navigate:se,fetch:Ve,revalidate:he,createHref:oe=>e.history.createHref(oe),encodeLocation:oe=>e.history.encodeLocation(oe),getFetcher:kt,resetFetcher:Nn,deleteFetcher:zn,dispose:me,getBlocker:It,deleteBlocker:Nt,patchRoutes:qn,_internalFetchControllers:F,_internalSetRoutes:Mn,_internalSetStateDoNotUseOrYouWillBreakYourApp(oe){J(oe)}},e.unstable_instrumentations&&(A=Xde(A,e.unstable_instrumentations.map(oe=>oe.router).filter(Boolean))),A}function afe(e,t){Et(e.length>0,"You must provide a non-empty routes array to createStaticHandler");let n={},r=(t?t.basename:null)||"/",a=t?.mapRouteProperties||hV,o=a;if(t?.unstable_instrumentations){let b=t.unstable_instrumentations;o=E=>({...a(E),...cV(b.map(x=>x.route).filter(Boolean),E)})}let i=fc(e,o,void 0,n);async function l(b,{requestContext:E,filterMatchesToLoad:x,skipLoaderErrorBubbling:w,skipRevalidation:S,dataStrategy:_,generateMiddlewareResponse:T}={}){let k=new URL(b.url),R=b.method,A=ri("",ga(k),null,"default"),C=Uo(i,A,r);if(E=E??new Mu,!y_(R)&&R!=="HEAD"){let M=Ar(405,{method:R}),{matches:L,route:j}=ju(i),B={basename:r,location:A,matches:L,loaderData:{},actionData:null,errors:{[j.id]:M},statusCode:M.status,loaderHeaders:{},actionHeaders:{}};return T?T(()=>Promise.resolve(B)):B}else if(!C){let M=Ar(404,{pathname:A.pathname}),{matches:L,route:j}=ju(i),B={basename:r,location:A,matches:L,loaderData:{},actionData:null,errors:{[j.id]:M},statusCode:M.status,loaderHeaders:{},actionHeaders:{}};return T?T(()=>Promise.resolve(B)):B}if(T){Et(E instanceof Mu,"When using middleware in `staticHandler.query()`, any provided `requestContext` must be an instance of `RouterContextProvider`");try{await UU(C,n,o);let M,L=await zU({request:b,unstable_pattern:Ys(C),matches:C,params:C[0].params,context:E},async()=>await T(async(B,K={})=>{let Z=await f(B,A,C,E,_||null,w===!0,null,"filterMatchesToLoad"in K?K.filterMatchesToLoad??null:x??null,S===!0);return ua(Z)?Z:(M={location:A,basename:r,...Z},M)}),async(j,B)=>{if(b_(j))return j;if(ua(j))try{j=new ws(j.status,j.statusText,await _V(j))}catch(K){j=K}if(ac(j)&&(j=kV(j)),M){B in M.loaderData&&(M.loaderData[B]=void 0);let K=ofe(i,M,j,w?B:wo(C,B).route.id);return T(()=>Promise.resolve(K))}else{let K=w?B:wo(C,C.find(te=>te.route.id===B||te.route.loader)?.route.id||B).route.id,Z={matches:C,location:A,basename:r,loaderData:{},actionData:null,errors:{[K]:j},statusCode:So(j)?j.status:500,actionHeaders:{},loaderHeaders:{}};return T(()=>Promise.resolve(Z))}});return Et(ua(L),"Expected a response in query()"),L}catch(M){if(ua(M))return M;throw M}}let O=await f(b,A,C,E,_||null,w===!0,null,x||null,S===!0);return ua(O)?O:{location:A,basename:r,...O}}async function u(b,{routeId:E,requestContext:x,dataStrategy:w,generateMiddlewareResponse:S}={}){let _=new URL(b.url),T=b.method,k=ri("",ga(_),null,"default"),R=Uo(i,k,r);if(x=x??new Mu,!y_(T)&&T!=="HEAD"&&T!=="OPTIONS")throw Ar(405,{method:T});if(!R)throw Ar(404,{pathname:k.pathname});let A=E?R.find(M=>M.route.id===E):Ju(R,k);if(E&&!A)throw Ar(403,{pathname:k.pathname,routeId:E});if(!A)throw Ar(404,{pathname:k.pathname});if(S)return Et(x instanceof Mu,"When using middleware in `staticHandler.queryRoute()`, any provided `requestContext` must be an instance of `RouterContextProvider`"),await UU(R,n,o),await zU({request:b,unstable_pattern:Ys(R),matches:R,params:R[0].params,context:x},async()=>await S(async j=>{let B=await f(j,k,R,x,w||null,!1,A,null,!1),K=O(B);return ua(K)?K:typeof K=="string"?new Response(K):Response.json(K)}),L=>{if(ac(L))return Promise.resolve(g_(L));if(ua(L))return Promise.resolve(L);throw L});let C=await f(b,k,R,x,w||null,!1,A,null,!1);return O(C);function O(M){if(ua(M))return M;let L=M.errors?Object.values(M.errors)[0]:void 0;if(L!==void 0)throw L;if(M.actionData)return Object.values(M.actionData)[0];if(M.loaderData)return Object.values(M.loaderData)[0]}}async function f(b,E,x,w,S,_,T,k,R){Et(b.signal,"query()/queryRoute() requests must contain an AbortController signal");try{if(Zr(b.method))return await m(b,x,T||Ju(x,E),w,S,_,T!=null,k,R);let A=await h(b,x,w,S,_,T,k);return ua(A)?A:{...A,actionData:null,actionHeaders:{}}}catch(A){if(AV(A)&&ua(A.result)){if(A.type==="error")throw A.result;return A.result}if(b_(A))return A;throw A}}async function m(b,E,x,w,S,_,T,k,R){let A;if(!x.route.action&&!x.route.lazy){let M=Ar(405,{method:b.method,pathname:new URL(b.url).pathname,routeId:x.route.id});if(T)throw M;A={type:"error",error:M}}else{let M=el(o,n,b,E,x,[],w);A=(await g(b,M,T,w,S))[x.route.id],b.signal.aborted&&DU(b,T)}if(Xi(A))throw new Response(null,{status:A.response.status,headers:{Location:A.response.headers.get("Location")}});if(T){if(zr(A))throw A.error;return{matches:[x],loaderData:{},actionData:{[x.route.id]:A.data},errors:null,statusCode:200,loaderHeaders:{},actionHeaders:{}}}if(R)if(zr(A)){let M=_?x:wo(E,x.route.id);return{statusCode:So(A.error)?A.error.status:A.statusCode!=null?A.statusCode:500,actionData:null,actionHeaders:{...A.headers?{[x.route.id]:A.headers}:{}},matches:E,loaderData:{},errors:{[M.route.id]:A.error},loaderHeaders:{}}}else return{actionData:{[x.route.id]:A.data},actionHeaders:A.headers?{[x.route.id]:A.headers}:{},matches:E,loaderData:{},errors:null,statusCode:A.statusCode||200,loaderHeaders:{}};let C=new Request(b.url,{headers:b.headers,redirect:b.redirect,signal:b.signal});if(zr(A)){let M=_?x:wo(E,x.route.id);return{...await h(C,E,w,S,_,null,k,[M.route.id,A]),statusCode:So(A.error)?A.error.status:A.statusCode!=null?A.statusCode:500,actionData:null,actionHeaders:{...A.headers?{[x.route.id]:A.headers}:{}}}}return{...await h(C,E,w,S,_,null,k),actionData:{[x.route.id]:A.data},...A.statusCode?{statusCode:A.statusCode}:{},actionHeaders:A.headers?{[x.route.id]:A.headers}:{}}}async function h(b,E,x,w,S,_,T,k){let R=_!=null;if(R&&!_?.route.loader&&!_?.route.lazy)throw Ar(400,{method:b.method,pathname:new URL(b.url).pathname,routeId:_?.route.id});let A;if(_)A=el(o,n,b,E,_,[],x);else{let M=k&&zr(k[1])?E.findIndex(j=>j.route.id===k[0])-1:void 0,L=Ys(E);A=E.map((j,B)=>M!=null&&B>M?bm(o,n,b,L,j,[],x,!1):bm(o,n,b,L,j,[],x,(j.route.loader||j.route.lazy)!=null&&(!T||T(j))))}if(!w&&!A.some(M=>M.shouldLoad))return{matches:E,loaderData:{},errors:k&&zr(k[1])?{[k[0]]:k[1].error}:null,statusCode:200,loaderHeaders:{}};let C=await g(b,A,R,x,w);return b.signal.aborted&&DU(b,R),{...CV(E,C,k,!0,S),matches:E}}async function g(b,E,x,w,S){let _=await SV(S||m_,b,E,null,w,!0),T={};return await Promise.all(E.map(async k=>{if(!(k.route.id in _))return;let R=_[k.route.id];if(IV(R)){let A=R.result;throw NV(A,b,k.route.id,E,r)}if(x){if(ua(R.result))throw R;if(ac(R.result))throw g_(R.result)}T[k.route.id]=await TV(R)})),T}return{dataRoutes:i,query:l,queryRoute:u}}function ofe(e,t,n,r){let a=r||t._deepestRenderedBoundaryId||e[0].id;return{...t,statusCode:So(n)?n.status:500,errors:{[a]:n}}}function DU(e,t){if(e.signal.reason!==void 0)throw e.signal.reason;let n=t?"queryRoute":"query";throw new Error(`${n}() call aborted without an \`AbortSignal.reason\`: ${e.method} ${e.url}`)}function sfe(e){return e!=null&&("formData"in e&&e.formData!=null||"body"in e&&e.body!==void 0)}function f_(e,t,n,r,a,o){let i,l;if(a){i=[];for(let f of t)if(i.push(f),f.route.id===a){l=f;break}}else i=t,l=t[t.length-1];let u=ow(r||".",aw(i),Na(e.pathname,n)||e.pathname,o==="path");if(r==null&&(u.search=e.search,u.hash=e.hash),(r==null||r===""||r===".")&&l){let f=rC(u.search);if(l.route.index&&!f)u.search=u.search?u.search.replace(/^\?/,"?index&"):"?index";else if(!l.route.index&&f){let m=new URLSearchParams(u.search),h=m.getAll("index");m.delete("index"),h.filter(b=>b).forEach(b=>m.append("index",b));let g=m.toString();u.search=g?`?${g}`:""}}return n!=="/"&&(u.pathname=Vde({basename:n,pathname:u.pathname})),ga(u)}function LU(e,t,n){if(!n||!sfe(n))return{path:t};if(n.formMethod&&!y_(n.formMethod))return{path:t,error:Ar(405,{method:n.formMethod})};let r=()=>({path:t,error:Ar(400,{type:"invalid-body"})}),o=(n.formMethod||"get").toUpperCase(),i=RV(t);if(n.body!==void 0){if(n.formEncType==="text/plain"){if(!Zr(o))return r();let h=typeof n.body=="string"?n.body:n.body instanceof FormData||n.body instanceof URLSearchParams?Array.from(n.body.entries()).reduce((g,[b,E])=>`${g}${b}=${E}
91
+ `)},Xie=0,bu=[];function Jie(e){var t=y.useRef([]),n=y.useRef([0,0]),r=y.useRef(),a=y.useState(Xie++)[0],o=y.useState(D5)[0],i=y.useRef(e);y.useEffect(function(){i.current=e},[e]),y.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var x=vie([e.lockRef.current],(e.shards||[]).map(pU),!0).filter(Boolean);return x.forEach(function(w){return w.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),x.forEach(function(w){return w.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var l=y.useCallback(function(x,w){if("touches"in x&&x.touches.length===2||x.type==="wheel"&&x.ctrlKey)return!i.current.allowPinchZoom;var S=kb(x),_=n.current,T="deltaX"in x?x.deltaX:_[0]-S[0],k="deltaY"in x?x.deltaY:_[1]-S[1],R,A=x.target,C=Math.abs(T)>Math.abs(k)?"h":"v";if("touches"in x&&C==="h"&&A.type==="range")return!1;var O=window.getSelection(),M=O&&O.anchorNode,L=M?M===A||M.contains(A):!1;if(L)return!1;var j=dU(C,A);if(!j)return!0;if(j?R=C:(R=C==="v"?"h":"v",j=dU(C,A)),!j)return!1;if(!r.current&&"changedTouches"in x&&(T||k)&&(r.current=R),!R)return!0;var B=r.current||R;return Yie(B,w,x,B==="h"?T:k)},[]),u=y.useCallback(function(x){var w=x;if(!(!bu.length||bu[bu.length-1]!==o)){var S="deltaY"in w?fU(w):kb(w),_=t.current.filter(function(R){return R.name===w.type&&(R.target===w.target||w.target===R.shadowParent)&&Zie(R.delta,S)})[0];if(_&&_.should){w.cancelable&&w.preventDefault();return}if(!_){var T=(i.current.shards||[]).map(pU).filter(Boolean).filter(function(R){return R.contains(w.target)}),k=T.length>0?l(w,T[0]):!i.current.noIsolation;k&&w.cancelable&&w.preventDefault()}}},[]),f=y.useCallback(function(x,w,S,_){var T={name:x,delta:w,target:S,should:_,shadowParent:Qie(S)};t.current.push(T),setTimeout(function(){t.current=t.current.filter(function(k){return k!==T})},1)},[]),m=y.useCallback(function(x){n.current=kb(x),r.current=void 0},[]),h=y.useCallback(function(x){f(x.type,fU(x),x.target,l(x,e.lockRef.current))},[]),g=y.useCallback(function(x){f(x.type,kb(x),x.target,l(x,e.lockRef.current))},[]);y.useEffect(function(){return bu.push(o),e.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:g}),document.addEventListener("wheel",u,gu),document.addEventListener("touchmove",u,gu),document.addEventListener("touchstart",m,gu),function(){bu=bu.filter(function(x){return x!==o}),document.removeEventListener("wheel",u,gu),document.removeEventListener("touchmove",u,gu),document.removeEventListener("touchstart",m,gu)}},[]);var b=e.removeScrollBar,E=e.inert;return y.createElement(y.Fragment,null,E?y.createElement(o,{styles:qie(a)}):null,b?y.createElement(Fie,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Qie(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const ele=Rie(O5,Jie);var Xm=y.forwardRef(function(e,t){return y.createElement(Zv,as({},e,{ref:t,sideCar:ele}))});Xm.classNames=Zv.classNames;var s_=["Enter"," "],tle=["ArrowDown","PageUp","Home"],P5=["ArrowUp","PageDown","End"],nle=[...tle,...P5],rle={ltr:[...s_,"ArrowRight"],rtl:[...s_,"ArrowLeft"]},ale={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Jm="Menu",[om,ole,sle]=NN(Jm),[Sc,$5]=qo(Jm,[sle,hl,_5]),qv=hl(),U5=_5(),[ile,_c]=Sc(Jm),[lle,Qm]=Sc(Jm),z5=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:o,modal:i=!0}=e,l=qv(t),[u,f]=y.useState(null),m=y.useRef(!1),h=ps(o),g=CN(a);return y.useEffect(()=>{const b=()=>{m.current=!0,document.addEventListener("pointerdown",E,{capture:!0,once:!0}),document.addEventListener("pointermove",E,{capture:!0,once:!0})},E=()=>m.current=!1;return document.addEventListener("keydown",b,{capture:!0}),()=>{document.removeEventListener("keydown",b,{capture:!0}),document.removeEventListener("pointerdown",E,{capture:!0}),document.removeEventListener("pointermove",E,{capture:!0})}},[]),d.jsx(Gv,{...l,children:d.jsx(ile,{scope:t,open:n,onOpenChange:h,content:u,onContentChange:f,children:d.jsx(lle,{scope:t,onClose:y.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:m,dir:g,modal:i,children:r})})})};z5.displayName=Jm;var cle="MenuAnchor",PN=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,a=qv(n);return d.jsx(Zm,{...a,...r,ref:t})});PN.displayName=cle;var $N="MenuPortal",[ule,F5]=Sc($N,{forceMount:void 0}),B5=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=e,o=_c($N,t);return d.jsx(ule,{scope:t,forceMount:n,children:d.jsx(ao,{present:n||o.open,children:d.jsx(af,{asChild:!0,container:a,children:r})})})};B5.displayName=$N;var Eo="MenuContent",[dle,UN]=Sc(Eo),H5=y.forwardRef((e,t)=>{const n=F5(Eo,e.__scopeMenu),{forceMount:r=n.forceMount,...a}=e,o=_c(Eo,e.__scopeMenu),i=Qm(Eo,e.__scopeMenu);return d.jsx(om.Provider,{scope:e.__scopeMenu,children:d.jsx(ao,{present:r||o.open,children:d.jsx(om.Slot,{scope:e.__scopeMenu,children:i.modal?d.jsx(fle,{...a,ref:t}):d.jsx(ple,{...a,ref:t})})})})}),fle=y.forwardRef((e,t)=>{const n=_c(Eo,e.__scopeMenu),r=y.useRef(null),a=gn(t,r);return y.useEffect(()=>{const o=r.current;if(o)return Yv(o)},[]),d.jsx(zN,{...e,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:lt(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),ple=y.forwardRef((e,t)=>{const n=_c(Eo,e.__scopeMenu);return d.jsx(zN,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),mle=cc("MenuContent.ScrollLock"),zN=y.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:a,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:b,disableOutsideScroll:E,...x}=e,w=_c(Eo,n),S=Qm(Eo,n),_=qv(n),T=U5(n),k=ole(n),[R,A]=y.useState(null),C=y.useRef(null),O=gn(t,C,w.onContentChange),M=y.useRef(0),L=y.useRef(""),j=y.useRef(0),B=y.useRef(null),K=y.useRef("right"),Z=y.useRef(0),te=E?Xm:y.Fragment,V=E?{as:mle,allowPinchZoom:!0}:void 0,Y=ae=>{const ee=L.current+ae,P=k().filter(W=>!W.disabled),H=document.activeElement,U=P.find(W=>W.ref.current===H)?.textValue,D=P.map(W=>W.textValue),$=Nle(D,ee,U),G=P.find(W=>W.textValue===$)?.ref.current;(function W(re){L.current=re,window.clearTimeout(M.current),re!==""&&(M.current=window.setTimeout(()=>W(""),1e3))})(ee),G&&setTimeout(()=>G.focus())};y.useEffect(()=>()=>window.clearTimeout(M.current),[]),zv();const F=y.useCallback(ae=>K.current===B.current?.side&&Rle(ae,B.current?.area),[]);return d.jsx(dle,{scope:n,searchRef:L,onItemEnter:y.useCallback(ae=>{F(ae)&&ae.preventDefault()},[F]),onItemLeave:y.useCallback(ae=>{F(ae)||(C.current?.focus(),A(null))},[F]),onTriggerLeave:y.useCallback(ae=>{F(ae)&&ae.preventDefault()},[F]),pointerGraceTimerRef:j,onPointerGraceIntentChange:y.useCallback(ae=>{B.current=ae},[]),children:d.jsx(te,{...V,children:d.jsx(Km,{asChild:!0,trapped:a,onMountAutoFocus:lt(o,ae=>{ae.preventDefault(),C.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:d.jsx(tf,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:b,children:d.jsx(mie,{asChild:!0,...T,dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:R,onCurrentTabStopIdChange:A,onEntryFocus:lt(u,ae=>{S.isUsingKeyboardRef.current||ae.preventDefault()}),preventScrollOnEntryFocus:!0,children:d.jsx(Wv,{role:"menu","aria-orientation":"vertical","data-state":oH(w.open),"data-radix-menu-content":"",dir:S.dir,..._,...x,ref:O,style:{outline:"none",...x.style},onKeyDown:lt(x.onKeyDown,ae=>{const P=ae.target.closest("[data-radix-menu-content]")===ae.currentTarget,H=ae.ctrlKey||ae.altKey||ae.metaKey,U=ae.key.length===1;P&&(ae.key==="Tab"&&ae.preventDefault(),!H&&U&&Y(ae.key));const D=C.current;if(ae.target!==D||!nle.includes(ae.key))return;ae.preventDefault();const G=k().filter(W=>!W.disabled).map(W=>W.ref.current);P5.includes(ae.key)&&G.reverse(),_le(G)}),onBlur:lt(e.onBlur,ae=>{ae.currentTarget.contains(ae.target)||(window.clearTimeout(M.current),L.current="")}),onPointerMove:lt(e.onPointerMove,sm(ae=>{const ee=ae.target,P=Z.current!==ae.clientX;if(ae.currentTarget.contains(ee)&&P){const H=ae.clientX>Z.current?"right":"left";K.current=H,Z.current=ae.clientX}}))})})})})})})});H5.displayName=Eo;var hle="MenuGroup",FN=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(Zt.div,{role:"group",...r,ref:t})});FN.displayName=hle;var gle="MenuLabel",V5=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(Zt.div,{...r,ref:t})});V5.displayName=gle;var Wy="MenuItem",mU="menu.itemSelect",Xv=y.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...a}=e,o=y.useRef(null),i=Qm(Wy,e.__scopeMenu),l=UN(Wy,e.__scopeMenu),u=gn(t,o),f=y.useRef(!1),m=()=>{const h=o.current;if(!n&&h){const g=new CustomEvent(mU,{bubbles:!0,cancelable:!0});h.addEventListener(mU,b=>r?.(b),{once:!0}),JB(h,g),g.defaultPrevented?f.current=!1:i.onClose()}};return d.jsx(G5,{...a,ref:u,disabled:n,onClick:lt(e.onClick,m),onPointerDown:h=>{e.onPointerDown?.(h),f.current=!0},onPointerUp:lt(e.onPointerUp,h=>{f.current||h.currentTarget?.click()}),onKeyDown:lt(e.onKeyDown,h=>{const g=l.searchRef.current!=="";n||g&&h.key===" "||s_.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});Xv.displayName=Wy;var G5=y.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:a,...o}=e,i=UN(Wy,n),l=U5(n),u=y.useRef(null),f=gn(t,u),[m,h]=y.useState(!1),[g,b]=y.useState("");return y.useEffect(()=>{const E=u.current;E&&b((E.textContent??"").trim())},[o.children]),d.jsx(om.ItemSlot,{scope:n,disabled:r,textValue:a??g,children:d.jsx(hie,{asChild:!0,...l,focusable:!r,children:d.jsx(Zt.div,{role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...o,ref:f,onPointerMove:lt(e.onPointerMove,sm(E=>{r?i.onItemLeave(E):(i.onItemEnter(E),E.defaultPrevented||E.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:lt(e.onPointerLeave,sm(E=>i.onItemLeave(E))),onFocus:lt(e.onFocus,()=>h(!0)),onBlur:lt(e.onBlur,()=>h(!1))})})})}),ble="MenuCheckboxItem",W5=y.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...a}=e;return d.jsx(X5,{scope:e.__scopeMenu,checked:n,children:d.jsx(Xv,{role:"menuitemcheckbox","aria-checked":Ky(n)?"mixed":n,...a,ref:t,"data-state":HN(n),onSelect:lt(a.onSelect,()=>r?.(Ky(n)?!0:!n),{checkForDefaultPrevented:!1})})})});W5.displayName=ble;var K5="MenuRadioGroup",[yle,vle]=Sc(K5,{value:void 0,onValueChange:()=>{}}),Y5=y.forwardRef((e,t)=>{const{value:n,onValueChange:r,...a}=e,o=ps(r);return d.jsx(yle,{scope:e.__scopeMenu,value:n,onValueChange:o,children:d.jsx(FN,{...a,ref:t})})});Y5.displayName=K5;var Z5="MenuRadioItem",q5=y.forwardRef((e,t)=>{const{value:n,...r}=e,a=vle(Z5,e.__scopeMenu),o=n===a.value;return d.jsx(X5,{scope:e.__scopeMenu,checked:o,children:d.jsx(Xv,{role:"menuitemradio","aria-checked":o,...r,ref:t,"data-state":HN(o),onSelect:lt(r.onSelect,()=>a.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});q5.displayName=Z5;var BN="MenuItemIndicator",[X5,wle]=Sc(BN,{checked:!1}),J5=y.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...a}=e,o=wle(BN,n);return d.jsx(ao,{present:r||Ky(o.checked)||o.checked===!0,children:d.jsx(Zt.span,{...a,ref:t,"data-state":HN(o.checked)})})});J5.displayName=BN;var xle="MenuSeparator",Q5=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(Zt.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Q5.displayName=xle;var Ele="MenuArrow",eH=y.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,a=qv(n);return d.jsx(Kv,{...a,...r,ref:t})});eH.displayName=Ele;var Sle="MenuSub",[UTe,tH]=Sc(Sle),Np="MenuSubTrigger",nH=y.forwardRef((e,t)=>{const n=_c(Np,e.__scopeMenu),r=Qm(Np,e.__scopeMenu),a=tH(Np,e.__scopeMenu),o=UN(Np,e.__scopeMenu),i=y.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=o,f={__scopeMenu:e.__scopeMenu},m=y.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return y.useEffect(()=>m,[m]),y.useEffect(()=>{const h=l.current;return()=>{window.clearTimeout(h),u(null)}},[l,u]),d.jsx(PN,{asChild:!0,...f,children:d.jsx(G5,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":a.contentId,"data-state":oH(n.open),...e,ref:fs(t,a.onTriggerChange),onClick:h=>{e.onClick?.(h),!(e.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:lt(e.onPointerMove,sm(h=>{o.onItemEnter(h),!h.defaultPrevented&&!e.disabled&&!n.open&&!i.current&&(o.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:lt(e.onPointerLeave,sm(h=>{m();const g=n.content?.getBoundingClientRect();if(g){const b=n.content?.dataset.side,E=b==="right",x=E?-5:5,w=g[E?"left":"right"],S=g[E?"right":"left"];o.onPointerGraceIntentChange({area:[{x:h.clientX+x,y:h.clientY},{x:w,y:g.top},{x:S,y:g.top},{x:S,y:g.bottom},{x:w,y:g.bottom}],side:b}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(h),h.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:lt(e.onKeyDown,h=>{const g=o.searchRef.current!=="";e.disabled||g&&h.key===" "||rle[r.dir].includes(h.key)&&(n.onOpenChange(!0),n.content?.focus(),h.preventDefault())})})})});nH.displayName=Np;var rH="MenuSubContent",aH=y.forwardRef((e,t)=>{const n=F5(Eo,e.__scopeMenu),{forceMount:r=n.forceMount,...a}=e,o=_c(Eo,e.__scopeMenu),i=Qm(Eo,e.__scopeMenu),l=tH(rH,e.__scopeMenu),u=y.useRef(null),f=gn(t,u);return d.jsx(om.Provider,{scope:e.__scopeMenu,children:d.jsx(ao,{present:r||o.open,children:d.jsx(om.Slot,{scope:e.__scopeMenu,children:d.jsx(zN,{id:l.contentId,"aria-labelledby":l.triggerId,...a,ref:f,align:"start",side:i.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{i.isUsingKeyboardRef.current&&u.current?.focus(),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:lt(e.onFocusOutside,m=>{m.target!==l.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:lt(e.onEscapeKeyDown,m=>{i.onClose(),m.preventDefault()}),onKeyDown:lt(e.onKeyDown,m=>{const h=m.currentTarget.contains(m.target),g=ale[i.dir].includes(m.key);h&&g&&(o.onOpenChange(!1),l.trigger?.focus(),m.preventDefault())})})})})})});aH.displayName=rH;function oH(e){return e?"open":"closed"}function Ky(e){return e==="indeterminate"}function HN(e){return Ky(e)?"indeterminate":e?"checked":"unchecked"}function _le(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Tle(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Nle(e,t,n){const a=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let i=Tle(e,Math.max(o,0));a.length===1&&(i=i.filter(f=>f!==n));const u=i.find(f=>f.toLowerCase().startsWith(a.toLowerCase()));return u!==n?u:void 0}function Cle(e,t){const{x:n,y:r}=e;let a=!1;for(let o=0,i=t.length-1;o<t.length;i=o++){const l=t[o],u=t[i],f=l.x,m=l.y,h=u.x,g=u.y;m>r!=g>r&&n<(h-f)*(r-m)/(g-m)+f&&(a=!a)}return a}function Rle(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Cle(n,t)}function sm(e){return t=>t.pointerType==="mouse"?e(t):void 0}var kle=z5,Ale=PN,Ile=B5,Ole=H5,Dle=FN,Lle=V5,Mle=Xv,jle=W5,Ple=Y5,$le=q5,Ule=J5,zle=Q5,Fle=eH,Ble=nH,Hle=aH,Jv="DropdownMenu",[Vle]=qo(Jv,[$5]),Ra=$5(),[Gle,sH]=Vle(Jv),iH=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:o,onOpenChange:i,modal:l=!0}=e,u=Ra(t),f=y.useRef(null),[m,h]=Qs({prop:a,defaultProp:o??!1,onChange:i,caller:Jv});return d.jsx(Gle,{scope:t,triggerId:oa(),triggerRef:f,contentId:oa(),open:m,onOpenChange:h,onOpenToggle:y.useCallback(()=>h(g=>!g),[h]),modal:l,children:d.jsx(kle,{...u,open:m,onOpenChange:h,dir:r,modal:l,children:n})})};iH.displayName=Jv;var lH="DropdownMenuTrigger",cH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...a}=e,o=sH(lH,n),i=Ra(n);return d.jsx(Ale,{asChild:!0,...i,children:d.jsx(Zt.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...a,ref:fs(t,o.triggerRef),onPointerDown:lt(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(o.onOpenToggle(),o.open||l.preventDefault())}),onKeyDown:lt(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&o.onOpenToggle(),l.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});cH.displayName=lH;var Wle="DropdownMenuPortal",uH=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Ra(t);return d.jsx(Ile,{...r,...n})};uH.displayName=Wle;var dH="DropdownMenuContent",fH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=sH(dH,n),o=Ra(n),i=y.useRef(!1);return d.jsx(Ole,{id:a.contentId,"aria-labelledby":a.triggerId,...o,...r,ref:t,onCloseAutoFocus:lt(e.onCloseAutoFocus,l=>{i.current||a.triggerRef.current?.focus(),i.current=!1,l.preventDefault()}),onInteractOutside:lt(e.onInteractOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0,m=u.button===2||f;(!a.modal||m)&&(i.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});fH.displayName=dH;var Kle="DropdownMenuGroup",Yle=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(Dle,{...a,...r,ref:t})});Yle.displayName=Kle;var Zle="DropdownMenuLabel",pH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(Lle,{...a,...r,ref:t})});pH.displayName=Zle;var qle="DropdownMenuItem",mH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(Mle,{...a,...r,ref:t})});mH.displayName=qle;var Xle="DropdownMenuCheckboxItem",hH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(jle,{...a,...r,ref:t})});hH.displayName=Xle;var Jle="DropdownMenuRadioGroup",gH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(Ple,{...a,...r,ref:t})});gH.displayName=Jle;var Qle="DropdownMenuRadioItem",bH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx($le,{...a,...r,ref:t})});bH.displayName=Qle;var ece="DropdownMenuItemIndicator",tce=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(Ule,{...a,...r,ref:t})});tce.displayName=ece;var nce="DropdownMenuSeparator",yH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(zle,{...a,...r,ref:t})});yH.displayName=nce;var rce="DropdownMenuArrow",ace=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(Fle,{...a,...r,ref:t})});ace.displayName=rce;var oce="DropdownMenuSubTrigger",vH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(Ble,{...a,...r,ref:t})});vH.displayName=oce;var sce="DropdownMenuSubContent",wH=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=Ra(n);return d.jsx(Hle,{...a,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});wH.displayName=sce;var ice=iH,lce=cH,cce=uH,xH=fH,EH=pH,SH=mH,uce=hH,dce=gH,_H=bH,TH=yH,fce=vH,pce=wH;const im=ice,lm=lce,mce=dce;fce.displayName;pce.displayName;function jd({ref:e,className:t,sideOffset:n=4,...r}){return d.jsx(cce,{children:d.jsx(xH,{ref:e,sideOffset:n,className:Ue("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...r})})}jd.displayName=xH.displayName;function Jr({ref:e,className:t,inset:n,...r}){return d.jsx(SH,{ref:e,className:Ue("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",n&&"pl-8",t),...r})}Jr.displayName=SH.displayName;uce.displayName;function ay({ref:e,className:t,children:n,...r}){return d.jsx(_H,{ref:e,className:Ue("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...r,children:n})}ay.displayName=_H.displayName;function i_({ref:e,className:t,inset:n,...r}){return d.jsx(EH,{ref:e,className:Ue("px-2 py-1.5 text-sm font-semibold",n&&"pl-8",t),...r})}i_.displayName=EH.displayName;function Lu({ref:e,className:t,...n}){return d.jsx(TH,{ref:e,className:Ue("-mx-1 my-1 h-px bg-muted",t),...n})}Lu.displayName=TH.displayName;function of({message:e,className:t="",vertical:n,noBorder:r}){return d.jsx("div",{className:Ue(`mt-2 rounded-md p-6 ${t}`,!r&&"border"),children:d.jsxs("p",{className:Ue("text-sm text-muted-foreground flex items-center gap-4",n&&"flex-col"),children:[d.jsx("svg",{width:"40",height:"40",viewBox:"0 0 273 273",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:"flex-shrink-0",children:d.jsx("g",{stroke:"none",strokeWidth:"1",fill:"none",fillRule:"evenodd",children:d.jsxs("g",{transform:"translate(5.320900, 5.320900)",fillRule:"nonzero",className:"stroke-black dark:stroke-white",strokeWidth:"4",children:[d.jsx("path",{d:"M49.953025,-2.10854389 C63.26892,-2.21867124 76.6185256,2.70621155 86.9019463,12.6653164 L86.9019463,12.6653164 L87.505627,13.2592944 C97.5154947,23.2654892 102.640454,36.3074513 102.880738,49.4222247 C103.08932,77.4533067 113.877287,105.391753 135.242867,126.757333 C156.613383,148.127849 184.559216,158.914875 212.568138,159.119313 L212.568138,159.119313 L213.212264,159.134159 C225.843948,159.517566 238.363557,164.434972 248.121998,173.886137 L248.121998,173.886137 L248.725621,174.480088 C258.982114,184.732164 264.11035,198.171134 264.11035,211.6101 C264.11035,225.04592 258.984514,238.481745 248.732867,248.732867 C238.592792,258.872942 225.336706,263.997882 212.046872,264.107794 C198.731075,264.21792 185.381569,259.293085 175.098248,249.334078 L175.098248,249.334078 L174.494602,248.740134 C163.75802,238.008189 158.640853,223.784027 159.143413,209.719372 C158.258245,182.640933 147.489786,155.83332 126.828333,135.171867 C106.351297,114.694831 79.8363505,103.934873 53.0237258,102.891841 L53.0237258,102.891841 L52.2811438,102.865674 C38.4791718,103.347421 24.5325234,98.4328111 13.8776628,88.1140866 L13.8776628,88.1140866 L13.2739843,87.5201168 C3.12895117,77.3789607 -1.9984796,64.1195994 -2.10841888,50.8264755 C-2.21854669,37.5105567 2.70635908,24.1609269 12.6655135,13.8774565 L12.6655135,13.8774565 L13.2594878,13.2737797 C23.4005926,3.12880025 36.659927,-1.99860507 49.953025,-2.10854389 Z"}),d.jsx("circle",{cx:"50",cy:"212.0001",r:"52.5"}),d.jsx("circle",{cx:"212.0001",cy:"50",r:"52.5"})]})})}),e]})})}function NH({className:e,color:t,children:n,grayscaled:r=!1}){const a=y.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[1]||"0")}return r?0:.2},[t,r]),o=y.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[0]||"0.5")}return r?.3:.4},[t,r]),i=y.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[2]||"0")}return Math.floor(Math.random()*360)},[t]),l=y.useMemo(()=>t||`oklch(${Math.min(o,1)} ${a} ${i})`,[i,a,o]),u=y.useMemo(()=>`oklch(${Math.min(o*2,1)} ${a} ${i})`,[i,a,o,t]),f=y.useMemo(()=>Math.floor(Math.random()*360),[i]),m=y.useMemo(()=>"1000%",[]);return d.jsx("section",{className:Ue("relative w-full h-full overflow-hidden",e),style:{background:`${u}`},children:d.jsxs("div",{className:"isolate relative w-full h-full",children:[d.jsx("div",{className:"noise w-full h-full",style:{background:`linear-gradient(${f}deg, ${l}, transparent), url(https://grainy-gradients.vercel.app/noise.svg)`,filter:`contrast(120%) brightness(${m})`}}),n&&d.jsx("div",{className:"relative z-10 w-full h-full",children:n})]})})}var CH=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),hce="VisuallyHidden",RH=y.forwardRef((e,t)=>d.jsx(Zt.span,{...e,ref:t,style:{...CH,...e.style}}));RH.displayName=hce;var gce=RH,[Qv]=qo("Tooltip",[hl]),ew=hl(),kH="TooltipProvider",bce=700,l_="tooltip.open",[yce,VN]=Qv(kH),AH=e=>{const{__scopeTooltip:t,delayDuration:n=bce,skipDelayDuration:r=300,disableHoverableContent:a=!1,children:o}=e,i=y.useRef(!0),l=y.useRef(!1),u=y.useRef(0);return y.useEffect(()=>{const f=u.current;return()=>window.clearTimeout(f)},[]),d.jsx(yce,{scope:t,isOpenDelayedRef:i,delayDuration:n,onOpen:y.useCallback(()=>{window.clearTimeout(u.current),i.current=!1},[]),onClose:y.useCallback(()=>{window.clearTimeout(u.current),u.current=window.setTimeout(()=>i.current=!0,r)},[r]),isPointerInTransitRef:l,onPointerInTransitChange:y.useCallback(f=>{l.current=f},[]),disableHoverableContent:a,children:o})};AH.displayName=kH;var cm="Tooltip",[vce,eh]=Qv(cm),IH=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:o,disableHoverableContent:i,delayDuration:l}=e,u=VN(cm,e.__scopeTooltip),f=ew(t),[m,h]=y.useState(null),g=oa(),b=y.useRef(0),E=i??u.disableHoverableContent,x=l??u.delayDuration,w=y.useRef(!1),[S,_]=Qs({prop:r,defaultProp:a??!1,onChange:C=>{C?(u.onOpen(),document.dispatchEvent(new CustomEvent(l_))):u.onClose(),o?.(C)},caller:cm}),T=y.useMemo(()=>S?w.current?"delayed-open":"instant-open":"closed",[S]),k=y.useCallback(()=>{window.clearTimeout(b.current),b.current=0,w.current=!1,_(!0)},[_]),R=y.useCallback(()=>{window.clearTimeout(b.current),b.current=0,_(!1)},[_]),A=y.useCallback(()=>{window.clearTimeout(b.current),b.current=window.setTimeout(()=>{w.current=!0,_(!0),b.current=0},x)},[x,_]);return y.useEffect(()=>()=>{b.current&&(window.clearTimeout(b.current),b.current=0)},[]),d.jsx(Gv,{...f,children:d.jsx(vce,{scope:t,contentId:g,open:S,stateAttribute:T,trigger:m,onTriggerChange:h,onTriggerEnter:y.useCallback(()=>{u.isOpenDelayedRef.current?A():k()},[u.isOpenDelayedRef,A,k]),onTriggerLeave:y.useCallback(()=>{E?R():(window.clearTimeout(b.current),b.current=0)},[R,E]),onOpen:k,onClose:R,disableHoverableContent:E,children:n})})};IH.displayName=cm;var c_="TooltipTrigger",OH=y.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,a=eh(c_,n),o=VN(c_,n),i=ew(n),l=y.useRef(null),u=gn(t,l,a.onTriggerChange),f=y.useRef(!1),m=y.useRef(!1),h=y.useCallback(()=>f.current=!1,[]);return y.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),d.jsx(Zm,{asChild:!0,...i,children:d.jsx(Zt.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...r,ref:u,onPointerMove:lt(e.onPointerMove,g=>{g.pointerType!=="touch"&&!m.current&&!o.isPointerInTransitRef.current&&(a.onTriggerEnter(),m.current=!0)}),onPointerLeave:lt(e.onPointerLeave,()=>{a.onTriggerLeave(),m.current=!1}),onPointerDown:lt(e.onPointerDown,()=>{a.open&&a.onClose(),f.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:lt(e.onFocus,()=>{f.current||a.onOpen()}),onBlur:lt(e.onBlur,a.onClose),onClick:lt(e.onClick,a.onClose)})})});OH.displayName=c_;var GN="TooltipPortal",[wce,xce]=Qv(GN,{forceMount:void 0}),DH=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:a}=e,o=eh(GN,t);return d.jsx(wce,{scope:t,forceMount:n,children:d.jsx(ao,{present:n||o.open,children:d.jsx(af,{asChild:!0,container:a,children:r})})})};DH.displayName=GN;var Pd="TooltipContent",LH=y.forwardRef((e,t)=>{const n=xce(Pd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:a="top",...o}=e,i=eh(Pd,e.__scopeTooltip);return d.jsx(ao,{present:r||i.open,children:i.disableHoverableContent?d.jsx(MH,{side:a,...o,ref:t}):d.jsx(Ece,{side:a,...o,ref:t})})}),Ece=y.forwardRef((e,t)=>{const n=eh(Pd,e.__scopeTooltip),r=VN(Pd,e.__scopeTooltip),a=y.useRef(null),o=gn(t,a),[i,l]=y.useState(null),{trigger:u,onClose:f}=n,m=a.current,{onPointerInTransitChange:h}=r,g=y.useCallback(()=>{l(null),h(!1)},[h]),b=y.useCallback((E,x)=>{const w=E.currentTarget,S={x:E.clientX,y:E.clientY},_=Nce(S,w.getBoundingClientRect()),T=Cce(S,_),k=Rce(x.getBoundingClientRect()),R=Ace([...T,...k]);l(R),h(!0)},[h]);return y.useEffect(()=>()=>g(),[g]),y.useEffect(()=>{if(u&&m){const E=w=>b(w,m),x=w=>b(w,u);return u.addEventListener("pointerleave",E),m.addEventListener("pointerleave",x),()=>{u.removeEventListener("pointerleave",E),m.removeEventListener("pointerleave",x)}}},[u,m,b,g]),y.useEffect(()=>{if(i){const E=x=>{const w=x.target,S={x:x.clientX,y:x.clientY},_=u?.contains(w)||m?.contains(w),T=!kce(S,i);_?g():T&&(g(),f())};return document.addEventListener("pointermove",E),()=>document.removeEventListener("pointermove",E)}},[u,m,i,f,g]),d.jsx(MH,{...e,ref:o})}),[Sce,_ce]=Qv(cm,{isInside:!1}),Tce=poe("TooltipContent"),MH=y.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":a,onEscapeKeyDown:o,onPointerDownOutside:i,...l}=e,u=eh(Pd,n),f=ew(n),{onClose:m}=u;return y.useEffect(()=>(document.addEventListener(l_,m),()=>document.removeEventListener(l_,m)),[m]),y.useEffect(()=>{if(u.trigger){const h=g=>{g.target?.contains(u.trigger)&&m()};return window.addEventListener("scroll",h,{capture:!0}),()=>window.removeEventListener("scroll",h,{capture:!0})}},[u.trigger,m]),d.jsx(tf,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:h=>h.preventDefault(),onDismiss:m,children:d.jsxs(Wv,{"data-state":u.stateAttribute,...f,...l,ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[d.jsx(Tce,{children:r}),d.jsx(Sce,{scope:n,isInside:!0,children:d.jsx(gce,{id:u.contentId,role:"tooltip",children:a||r})})]})})});LH.displayName=Pd;var jH="TooltipArrow",PH=y.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,a=ew(n);return _ce(jH,n).isInside?null:d.jsx(Kv,{...a,...r,ref:t})});PH.displayName=jH;function Nce(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),a=Math.abs(t.right-e.x),o=Math.abs(t.left-e.x);switch(Math.min(n,r,a,o)){case o:return"left";case a:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Cce(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function Rce(e){const{top:t,right:n,bottom:r,left:a}=e;return[{x:a,y:t},{x:n,y:t},{x:n,y:r},{x:a,y:r}]}function kce(e,t){const{x:n,y:r}=e;let a=!1;for(let o=0,i=t.length-1;o<t.length;i=o++){const l=t[o],u=t[i],f=l.x,m=l.y,h=u.x,g=u.y;m>r!=g>r&&n<(h-f)*(r-m)/(g-m)+f&&(a=!a)}return a}function Ace(e){const t=e.slice();return t.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),Ice(t)}function Ice(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const a=e[r];for(;t.length>=2;){const o=t[t.length-1],i=t[t.length-2];if((o.x-i.x)*(a.y-i.y)>=(o.y-i.y)*(a.x-i.x))t.pop();else break}t.push(a)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const a=e[r];for(;n.length>=2;){const o=n[n.length-1],i=n[n.length-2];if((o.x-i.x)*(a.y-i.y)>=(o.y-i.y)*(a.x-i.x))n.pop();else break}n.push(a)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var Oce=AH,Dce=IH,Lce=OH,Mce=DH,jce=LH,Pce=PH;function WN({delayDuration:e=0,...t}){return d.jsx(Oce,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Wt({...e}){return d.jsx(WN,{children:d.jsx(Dce,{"data-slot":"tooltip",...e})})}function Kt({...e}){return d.jsx(Lce,{"data-slot":"tooltip-trigger",...e})}function Yt({className:e,sideOffset:t=0,children:n,...r}){return d.jsx(Mce,{children:d.jsxs(jce,{"data-slot":"tooltip-content",sideOffset:t,className:Ue("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...r,children:[n,d.jsx(Pce,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}class $ce{name="mcp_inspector_open";properties;constructor(t){this.properties={server_url:t.serverUrl,connection_count:t.connectionCount}}}class hU{name="mcp_tool_execution";properties;constructor(t){this.properties={tool_name:t.toolName,server_id:t.serverId,success:t.success,duration:t.duration,error:t.error}}}class gU{name="mcp_resource_read";properties;constructor(t){this.properties={resource_uri:t.resourceUri,server_id:t.serverId,success:t.success,error:t.error}}}class bU{name="mcp_prompt_call";properties;constructor(t){this.properties={prompt_name:t.promptName,server_id:t.serverId,success:t.success,error:t.error}}}class yU{name="mcp_chat_message";properties;constructor(t){this.properties={server_id:t.serverId,provider:t.provider,model:t.model,message_count:t.messageCount,tool_calls_count:t.toolCallsCount,success:t.success,execution_mode:t.executionMode,duration:t.duration,error:t.error}}}class Uce{name="mcp_server_added";properties;constructor(t){this.properties={server_id:t.serverId,server_url:t.serverUrl,connection_type:t.connectionType,via_proxy:t.viaProxy}}}class zce{name="mcp_command_palette_open";properties;constructor(t){this.properties={trigger:t.trigger}}}class Fce{name="mcp_tool_saved";properties;constructor(t){this.properties={tool_name:t.toolName,server_id:t.serverId}}}function LE(){try{return"0.14.4"}catch{return"0.0.0"}}var Bce={};function ME(){try{return typeof window<"u"&&typeof document<"u"}catch{return!1}}class vU{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,r=setTimeout(()=>n.abort(),this.timeout),a=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(r),!a.ok)throw new Error(`HTTP error! status: ${a.status}`)}catch{}}}function Pi(e){return`mcp_inspector_telemetry_${e}`}class ra{static instance=null;POSTHOG_PROXY_URL="/inspector/api/tel/posthog";SCARF_PROXY_URL="/inspector/api/tel/scarf";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogClient=null;_scarfClient=null;_source="inspector";constructor(){const t=ME(),n=this.isTelemetryDisabled();if(this._source=this.getStoredSource()||"inspector",n)this._posthogClient=null,this._scarfClient=null;else if(!t)this._posthogClient=null,this._scarfClient=null;else{try{this._posthogClient=new vU(this.POSTHOG_PROXY_URL,3e3)}catch{this._posthogClient=null}try{this._scarfClient=new vU(this.SCARF_PROXY_URL,3e3)}catch{this._scarfClient=null}}}isTelemetryDisabled(){return typeof localStorage<"u"&&localStorage.getItem(Pi("disabled"))==="true"||typeof process<"u"&&Bce?.MCP_USE_ANONYMIZED_TELEMETRY==="false"}getStoredSource(){return typeof localStorage<"u"?localStorage.getItem(Pi("source")):null}static getInstance(){return ra.instance||(ra.instance=new ra),ra.instance}setSource(t){this._source=t,typeof localStorage<"u"&&localStorage.setItem(Pi("source"),t)}getSource(){return this._source}get userId(){if(this._currUserId)return this._currUserId;if(!ME())return this._currUserId=this.UNKNOWN_USER_ID,this._currUserId;try{const t=localStorage.getItem(Pi("user_id"));if(t)this._currUserId=t;else{const n=this.generateUserId();localStorage.setItem(Pi("user_id"),n),this._currUserId=n}this.trackPackageDownload({triggered_by:"user_id_property"}).catch(()=>{})}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}generateUserId(){const t=window.crypto;if(t){const n=new Uint8Array(16);t.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;const r=Array.from(n).map(a=>a.toString(16).padStart(2,"0")).join("");return r.slice(0,8)+"-"+r.slice(8,12)+"-"+r.slice(12,16)+"-"+r.slice(16,20)+"-"+r.slice(20,32)}else return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const r=Math.random()*16|0;return(n==="x"?r:r&3|8).toString(16)})}async capture(t){if(!(!this._posthogClient&&!this._scarfClient)){if(this._posthogClient)try{const n={event:t.name,user_id:this.userId,properties:{...t.properties,mcp_use_version:LE(),language:"typescript",source:this._source,package:"inspector"}};await this._posthogClient.logEvent(n)}catch{}if(this._scarfClient)try{const n={};n.mcp_use_version=LE(),n.user_id=this.userId,n.event=t.name,n.language="typescript",n.source=this._source,n.package="inspector",await this._scarfClient.logEvent(n)}catch{}}}async trackPackageDownload(t){if(this._scarfClient&&ME())try{const n=LE();let r=!1,a=!1;const o=localStorage.getItem(Pi("download_version"));if(o?n>o&&(r=!0,a=!1,localStorage.setItem(Pi("download_version"),n)):(r=!0,a=!0,localStorage.setItem(Pi("download_version"),n)),r){const i={...t||{}};i.mcp_use_version=n,i.user_id=this.userId,i.event="package_download",i.first_download=a,i.language="typescript",i.source=this._source,i.package="inspector",await this._scarfClient.logEvent(i)}}catch{}}async trackInspectorOpen(t){const n=new $ce(t);await this.capture(n)}}const Hce=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Vce=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),wU=e=>{const t=Vce(e);return t.charAt(0).toUpperCase()+t.slice(1)},$H=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),Gce=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var Wce={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Kce=y.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:o,iconNode:i,...l},u)=>y.createElement("svg",{ref:u,...Wce,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:$H("lucide",a),...!o&&!Gce(l)&&{"aria-hidden":"true"},...l},[...i.map(([f,m])=>y.createElement(f,m)),...Array.isArray(o)?o:[o]]));const gt=(e,t)=>{const n=y.forwardRef(({className:r,...a},o)=>y.createElement(Kce,{ref:o,iconNode:t,className:$H(`lucide-${Hce(wU(e))}`,`lucide-${e}`,r),...a}));return n.displayName=wU(e),n};const Yce=[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]],Zce=gt("arrow-down-to-line",Yce);const qce=[["path",{d:"m18 9-6-6-6 6",key:"kcunyi"}],["path",{d:"M12 3v14",key:"7cf3v8"}],["path",{d:"M5 21h14",key:"11awu3"}]],Xce=gt("arrow-up-from-line",qce);const Jce=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Qce=gt("arrow-up",Jce);const eue=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],KN=gt("bell",eue);const tue=[["path",{d:"m11 10 3 3",key:"fzmg1i"}],["path",{d:"M6.5 21A3.5 3.5 0 1 0 3 17.5a2.62 2.62 0 0 1-.708 1.792A1 1 0 0 0 3 21z",key:"p4q2r7"}],["path",{d:"M9.969 17.031 21.378 5.624a1 1 0 0 0-3.002-3.002L6.967 14.031",key:"wy6l02"}]],UH=gt("brush",tue);const nue=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],rue=gt("bug",nue);const aue=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Or=gt("check",aue);const oue=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],hs=gt("chevron-down",oue);const sue=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],tw=gt("chevron-left",sue);const iue=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],zH=gt("chevron-right",iue);const lue=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],cue=gt("chevron-up",lue);const uue=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],due=gt("chevrons-up-down",uue);const fue=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}]],xU=gt("circle-minus",fue);const pue=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],um=gt("clock",pue);const mue=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],YN=gt("code",mue);const hue=[["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["circle",{cx:"12",cy:"12",r:"8",key:"46899m"}]],gue=gt("cog",hue);const bue=[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]],yue=gt("command",bue);const vue=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],wr=gt("copy",vue);const wue=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],nw=gt("database",wue);const xue=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],th=gt("download",xue);const Eue=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],Sue=gt("ellipsis-vertical",Eue);const _ue=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],u_=gt("external-link",_ue);const Tue=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],FH=gt("eye-off",Tue);const Nue=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],d_=gt("eye",Nue);const Cue=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],Rue=gt("file-code",Cue);const kue=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]],Aue=gt("file-image",kue);const Iue=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],ZN=gt("file-text",Iue);const Oue=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],Due=gt("file",Oue);const Lue=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],Mue=gt("folder-open",Lue);const jue=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Pue=gt("globe",jue);const $ue=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],Uue=gt("grip-vertical",$ue);const zue=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],BH=gt("hash",zue);const Fue=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],dm=gt("history",Fue);const Bue=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Up=gt("info",Bue);const Hue=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],HH=gt("key",Hue);const Vue=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],cl=gt("loader-circle",Vue);const Gue=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],qN=gt("maximize-2",Gue);const Wue=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]],fm=gt("maximize",Wue);const Kue=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],Yue=gt("message-circle",Kue);const Zue=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],pm=gt("message-square",Zue);const que=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]],VH=gt("minimize",que);const Xue=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],EU=gt("monitor",Xue);const Jue=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],SU=gt("moon",Jue);const Que=[["path",{d:"M2 10h6V4",key:"zwrco"}],["path",{d:"m2 4 6 6",key:"ug085t"}],["path",{d:"M21 10V7a2 2 0 0 0-2-2h-7",key:"git5jr"}],["path",{d:"M3 14v2a2 2 0 0 0 2 2h3",key:"1f7fh3"}],["rect",{x:"12",y:"14",width:"10",height:"7",rx:"1",key:"1wjs3o"}]],ede=gt("picture-in-picture",Que);const tde=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],GH=gt("play",tde);const nde=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],mm=gt("plus",nde);const rde=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],_U=gt("rotate-ccw",rde);const ade=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],XN=gt("save",ade);const ode=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],sf=gt("search",ode);const sde=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],ide=gt("send",sde);const lde=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],WH=gt("server",lde);const cde=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Xu=gt("settings",cde);const ude=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],dde=gt("shield",ude);const fde=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],pde=gt("sparkles",fde);const mde=[["path",{d:"M21 10.656V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.344",key:"2acyp4"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],KH=gt("square-check-big",mde);const hde=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],gde=gt("square-pen",hde);const bde=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 4h.01",key:"1ujb9j"}],["path",{d:"M20 12h.01",key:"1ykeid"}],["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M4 12h.01",key:"158zrr"}],["path",{d:"M17.657 6.343h.01",key:"31pqzk"}],["path",{d:"M17.657 17.657h.01",key:"jehnf4"}],["path",{d:"M6.343 17.657h.01",key:"gdk6ow"}],["path",{d:"M6.343 6.343h.01",key:"1uurf0"}]],TU=gt("sun-dim",bde);const yde=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],jE=gt("terminal",yde);const vde=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],ni=gt("trash-2",vde);const wde=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],xde=gt("trash",wde);const Ede=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],dc=gt("wrench",Ede);const Sde=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],vs=gt("x",Sde);const _de=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],hm=gt("zap",_de);var YH=e=>{throw TypeError(e)},Tde=(e,t,n)=>t.has(e)||YH("Cannot "+n),PE=(e,t,n)=>(Tde(e,t,"read from private field"),n?n.call(e):t.get(e)),Nde=(e,t,n)=>t.has(e)?YH("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Cde=(e=>(e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE",e))(Cde||{}),NU="popstate";function ZH(e={}){let{initialEntries:t=["/"],initialIndex:n,v5Compat:r=!1}=e,a;a=t.map((b,E)=>m(b,typeof b=="string"?null:b.state,E===0?"default":void 0));let o=u(n??a.length-1),i="POP",l=null;function u(b){return Math.min(Math.max(b,0),a.length-1)}function f(){return a[o]}function m(b,E=null,x){let w=ri(a?f().pathname:"/",b,E,x);return Un(w.pathname.charAt(0)==="/",`relative pathnames are not supported in memory history: ${JSON.stringify(b)}`),w}function h(b){return typeof b=="string"?b:ga(b)}return{get index(){return o},get action(){return i},get location(){return f()},createHref:h,createURL(b){return new URL(h(b),"http://localhost")},encodeLocation(b){let E=typeof b=="string"?Ro(b):b;return{pathname:E.pathname||"",search:E.search||"",hash:E.hash||""}},push(b,E){i="PUSH";let x=m(b,E);o+=1,a.splice(o,a.length,x),r&&l&&l({action:i,location:x,delta:1})},replace(b,E){i="REPLACE";let x=m(b,E);a[o]=x,r&&l&&l({action:i,location:x,delta:0})},go(b){i="POP";let E=u(o+b),x=a[E];o=E,l&&l({action:i,location:x,delta:b})},listen(b){return l=b,()=>{l=null}}}}function qH(e={}){function t(r,a){let{pathname:o,search:i,hash:l}=r.location;return ri("",{pathname:o,search:i,hash:l},a.state&&a.state.usr||null,a.state&&a.state.key||"default")}function n(r,a){return typeof a=="string"?a:ga(a)}return JH(t,n,null,e)}function XH(e={}){function t(a,o){let{pathname:i="/",search:l="",hash:u=""}=Ro(a.location.hash.substring(1));return!i.startsWith("/")&&!i.startsWith(".")&&(i="/"+i),ri("",{pathname:i,search:l,hash:u},o.state&&o.state.usr||null,o.state&&o.state.key||"default")}function n(a,o){let i=a.document.querySelector("base"),l="";if(i&&i.getAttribute("href")){let u=a.location.href,f=u.indexOf("#");l=f===-1?u:u.slice(0,f)}return l+"#"+(typeof o=="string"?o:ga(o))}function r(a,o){Un(a.pathname.charAt(0)==="/",`relative pathnames are not supported in hash history.push(${JSON.stringify(o)})`)}return JH(t,n,r,e)}function Et(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Un(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function Rde(){return Math.random().toString(36).substring(2,10)}function CU(e,t){return{usr:e.state,key:e.key,idx:t}}function ri(e,t,n=null,r){return{pathname:typeof e=="string"?e:e.pathname,search:"",hash:"",...typeof t=="string"?Ro(t):t,state:n,key:t&&t.key||r||Rde()}}function ga({pathname:e="/",search:t="",hash:n=""}){return t&&t!=="?"&&(e+=t.charAt(0)==="?"?t:"?"+t),n&&n!=="#"&&(e+=n.charAt(0)==="#"?n:"#"+n),e}function Ro(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function JH(e,t,n,r={}){let{window:a=document.defaultView,v5Compat:o=!1}=r,i=a.history,l="POP",u=null,f=m();f==null&&(f=0,i.replaceState({...i.state,idx:f},""));function m(){return(i.state||{idx:null}).idx}function h(){l="POP";let w=m(),S=w==null?null:w-f;f=w,u&&u({action:l,location:x.location,delta:S})}function g(w,S){l="PUSH";let _=ri(x.location,w,S);n&&n(_,w),f=m()+1;let T=CU(_,f),k=x.createHref(_);try{i.pushState(T,"",k)}catch(R){if(R instanceof DOMException&&R.name==="DataCloneError")throw R;a.location.assign(k)}o&&u&&u({action:l,location:x.location,delta:1})}function b(w,S){l="REPLACE";let _=ri(x.location,w,S);n&&n(_,w),f=m();let T=CU(_,f),k=x.createHref(_);i.replaceState(T,"",k),o&&u&&u({action:l,location:x.location,delta:0})}function E(w){return QH(w)}let x={get action(){return l},get location(){return e(a,i)},listen(w){if(u)throw new Error("A history only accepts one active listener");return a.addEventListener(NU,h),u=w,()=>{a.removeEventListener(NU,h),u=null}},createHref(w){return t(a,w)},createURL:E,encodeLocation(w){let S=E(w);return{pathname:S.pathname,search:S.search,hash:S.hash}},push:g,replace:b,go(w){return i.go(w)}};return x}function QH(e,t=!1){let n="http://localhost";typeof window<"u"&&(n=window.location.origin!=="null"?window.location.origin:window.location.href),Et(n,"No window.location.(origin|href) available to create URL");let r=typeof e=="string"?e:ga(e);return r=r.replace(/ $/,"%20"),!t&&r.startsWith("//")&&(r=n+r),new URL(r,n)}function zTe(e){return{defaultValue:e}}var Cp,Mu=class{constructor(e){if(Nde(this,Cp,new Map),e)for(let[t,n]of e)this.set(t,n)}get(e){if(PE(this,Cp).has(e))return PE(this,Cp).get(e);if(e.defaultValue!==void 0)return e.defaultValue;throw new Error("No value found for context")}set(e,t){PE(this,Cp).set(e,t)}};Cp=new WeakMap;var kde=new Set(["lazy","caseSensitive","path","id","index","children"]);function Ade(e){return kde.has(e)}var Ide=new Set(["lazy","caseSensitive","path","id","index","middleware","children"]);function Ode(e){return Ide.has(e)}function Dde(e){return e.index===!0}function fc(e,t,n=[],r={},a=!1){return e.map((o,i)=>{let l=[...n,String(i)],u=typeof o.id=="string"?o.id:l.join("-");if(Et(o.index!==!0||!o.children,"Cannot specify children on an index route"),Et(a||!r[u],`Found a route id collision on id "${u}". Route id's must be globally unique within Data Router usages`),Dde(o)){let f={...o,id:u};return r[u]=RU(f,t(f)),f}else{let f={...o,id:u,children:void 0};return r[u]=RU(f,t(f)),o.children&&(f.children=fc(o.children,t,l,r,a)),f}})}function RU(e,t){return Object.assign(e,{...t,...typeof t.lazy=="object"&&t.lazy!=null?{lazy:{...e.lazy,...t.lazy}}:{}})}function Uo(e,t,n="/"){return Rp(e,t,n,!1)}function Rp(e,t,n,r){let a=typeof t=="string"?Ro(t):t,o=Na(a.pathname||"/",n);if(o==null)return null;let i=tV(e);Lde(i);let l=null;for(let u=0;l==null&&u<i.length;++u){let f=aV(o);l=Hde(i[u],f,r)}return l}function eV(e,t){let{route:n,pathname:r,params:a}=e;return{id:n.id,pathname:r,params:a,data:t[n.id],loaderData:t[n.id],handle:n.handle}}function tV(e,t=[],n=[],r="",a=!1){let o=(i,l,u=a,f)=>{let m={relativePath:f===void 0?i.path||"":f,caseSensitive:i.caseSensitive===!0,childrenIndex:l,route:i};if(m.relativePath.startsWith("/")){if(!m.relativePath.startsWith(r)&&u)return;Et(m.relativePath.startsWith(r),`Absolute route path "${m.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),m.relativePath=m.relativePath.slice(r.length)}let h=is([r,m.relativePath]),g=n.concat(m);i.children&&i.children.length>0&&(Et(i.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${h}".`),tV(i.children,t,g,h,u)),!(i.path==null&&!i.index)&&t.push({path:h,score:Fde(h,i.index),routesMeta:g})};return e.forEach((i,l)=>{if(i.path===""||!i.path?.includes("?"))o(i,l);else for(let u of nV(i.path))o(i,l,!0,u)}),t}function nV(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,a=n.endsWith("?"),o=n.replace(/\?$/,"");if(r.length===0)return a?[o,""]:[o];let i=nV(r.join("/")),l=[];return l.push(...i.map(u=>u===""?o:[o,u].join("/"))),a&&l.push(...i),l.map(u=>e.startsWith("/")&&u===""?"/":u)}function Lde(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:Bde(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}var Mde=/^:[\w-]+$/,jde=3,Pde=2,$de=1,Ude=10,zde=-2,kU=e=>e==="*";function Fde(e,t){let n=e.split("/"),r=n.length;return n.some(kU)&&(r+=zde),t&&(r+=Pde),n.filter(a=>!kU(a)).reduce((a,o)=>a+(Mde.test(o)?jde:o===""?$de:Ude),r)}function Bde(e,t){return e.length===t.length&&e.slice(0,-1).every((r,a)=>r===t[a])?e[e.length-1]-t[t.length-1]:0}function Hde(e,t,n=!1){let{routesMeta:r}=e,a={},o="/",i=[];for(let l=0;l<r.length;++l){let u=r[l],f=l===r.length-1,m=o==="/"?t:t.slice(o.length)||"/",h=gm({path:u.relativePath,caseSensitive:u.caseSensitive,end:f},m),g=u.route;if(!h&&f&&n&&!r[r.length-1].route.index&&(h=gm({path:u.relativePath,caseSensitive:u.caseSensitive,end:!1},m)),!h)return null;Object.assign(a,h.params),i.push({params:a,pathname:is([o,h.pathname]),pathnameBase:Wde(is([o,h.pathnameBase])),route:g}),h.pathnameBase!=="/"&&(o=is([o,h.pathnameBase]))}return i}function FTe(e,t={}){let n=e;n.endsWith("*")&&n!=="*"&&!n.endsWith("/*")&&(Un(!1,`Route path "${n}" will be treated as if it were "${n.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${n.replace(/\*$/,"/*")}".`),n=n.replace(/\*$/,"/*"));const r=n.startsWith("/")?"/":"",a=i=>i==null?"":typeof i=="string"?i:String(i),o=n.split(/\/+/).map((i,l,u)=>{if(l===u.length-1&&i==="*")return a(t["*"]);const m=i.match(/^:([\w-]+)(\??)(.*)/);if(m){const[,h,g,b]=m;let E=t[h];return Et(g==="?"||E!=null,`Missing ":${h}" param`),encodeURIComponent(a(E))+b}return i.replace(/\?$/g,"")}).filter(i=>!!i);return r+o.join("/")}function gm(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=rV(e.path,e.caseSensitive,e.end),a=t.match(n);if(!a)return null;let o=a[0],i=o.replace(/(.)\/+$/,"$1"),l=a.slice(1);return{params:r.reduce((f,{paramName:m,isOptional:h},g)=>{if(m==="*"){let E=l[g]||"";i=o.slice(0,o.length-E.length).replace(/(.)\/+$/,"$1")}const b=l[g];return h&&!b?f[m]=void 0:f[m]=(b||"").replace(/%2F/g,"/"),f},{}),pathname:o,pathnameBase:i,pattern:e}}function rV(e,t=!1,n=!0){Un(e==="*"||!e.endsWith("*")||e.endsWith("/*"),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,"/*")}".`);let r=[],a="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(i,l,u)=>(r.push({paramName:l,isOptional:u!=null}),u?"/?([^\\/]+)?":"/([^\\/]+)")).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return e.endsWith("*")?(r.push({paramName:"*"}),a+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?a+="\\/*$":e!==""&&e!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),r]}function aV(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Un(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function Na(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function Vde({basename:e,pathname:t}){return t==="/"?e:is([e,t])}var oV=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,rw=e=>oV.test(e);function Gde(e,t="/"){let{pathname:n,search:r="",hash:a=""}=typeof e=="string"?Ro(e):e,o;if(n)if(rw(n))o=n;else{if(n.includes("//")){let i=n;n=n.replace(/\/\/+/g,"/"),Un(!1,`Pathnames cannot have embedded double slashes - normalizing ${i} -> ${n}`)}n.startsWith("/")?o=AU(n.substring(1),"/"):o=AU(n,t)}else o=t;return{pathname:o,search:Kde(r),hash:Yde(a)}}function AU(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(a=>{a===".."?n.length>1&&n.pop():a!=="."&&n.push(a)}),n.length>1?n.join("/"):"/"}function $E(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function sV(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function aw(e){let t=sV(e);return t.map((n,r)=>r===t.length-1?n.pathname:n.pathnameBase)}function ow(e,t,n,r=!1){let a;typeof e=="string"?a=Ro(e):(a={...e},Et(!a.pathname||!a.pathname.includes("?"),$E("?","pathname","search",a)),Et(!a.pathname||!a.pathname.includes("#"),$E("#","pathname","hash",a)),Et(!a.search||!a.search.includes("#"),$E("#","search","hash",a)));let o=e===""||a.pathname==="",i=o?"/":a.pathname,l;if(i==null)l=n;else{let h=t.length-1;if(!r&&i.startsWith("..")){let g=i.split("/");for(;g[0]==="..";)g.shift(),h-=1;a.pathname=g.join("/")}l=h>=0?t[h]:"/"}let u=Gde(a,l),f=i&&i!=="/"&&i.endsWith("/"),m=(o||i===".")&&n.endsWith("/");return!u.pathname.endsWith("/")&&(f||m)&&(u.pathname+="/"),u}var is=e=>e.join("/").replace(/\/\/+/g,"/"),Wde=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),Kde=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,Yde=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e,Zde=class{constructor(e,t){this.type="DataWithResponseInit",this.data=e,this.init=t||null}};function qde(e,t){return new Zde(e,typeof t=="number"?{status:t}:t)}var JN=(e,t=302)=>{let n=t;typeof n=="number"?n={status:n}:typeof n.status>"u"&&(n.status=302);let r=new Headers(n.headers);return r.set("Location",e),new Response(null,{...n,headers:r})},BTe=(e,t)=>{let n=JN(e,t);return n.headers.set("X-Remix-Reload-Document","true"),n},HTe=(e,t)=>{let n=JN(e,t);return n.headers.set("X-Remix-Replace","true"),n},ws=class{constructor(e,t,n,r=!1){this.status=e,this.statusText=t||"",this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function So(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}function Ys(e){return e.map(t=>t.route.path).filter(Boolean).join("/").replace(/\/\/*/g,"/")||"/"}var iV=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function lV(e,t){let n=e;if(typeof n!="string"||!oV.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,a=!1;if(iV)try{let o=new URL(window.location.href),i=n.startsWith("//")?new URL(o.protocol+n):new URL(n),l=Na(i.pathname,t);i.origin===o.origin&&l!=null?n=l+i.search+i.hash:a=!0}catch{Un(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:a,to:n}}var qi=Symbol("Uninstrumented");function cV(e,t){let n={lazy:[],"lazy.loader":[],"lazy.action":[],"lazy.middleware":[],middleware:[],loader:[],action:[]};e.forEach(a=>a({id:t.id,index:t.index,path:t.path,instrument(o){let i=Object.keys(n);for(let l of i)o[l]&&n[l].push(o[l])}}));let r={};if(typeof t.lazy=="function"&&n.lazy.length>0){let a=Ql(n.lazy,t.lazy,()=>{});a&&(r.lazy=a)}if(typeof t.lazy=="object"){let a=t.lazy;["middleware","loader","action"].forEach(o=>{let i=a[o],l=n[`lazy.${o}`];if(typeof i=="function"&&l.length>0){let u=Ql(l,i,()=>{});u&&(r.lazy=Object.assign(r.lazy||{},{[o]:u}))}})}return["loader","action"].forEach(a=>{let o=t[a];if(typeof o=="function"&&n[a].length>0){let i=o[qi]??o,l=Ql(n[a],i,(...u)=>IU(u[0]));l&&(a==="loader"&&i.hydrate===!0&&(l.hydrate=!0),l[qi]=i,r[a]=l)}}),t.middleware&&t.middleware.length>0&&n.middleware.length>0&&(r.middleware=t.middleware.map(a=>{let o=a[qi]??a,i=Ql(n.middleware,o,(...l)=>IU(l[0]));return i?(i[qi]=o,i):a})),r}function Xde(e,t){let n={navigate:[],fetch:[]};if(t.forEach(r=>r({instrument(a){let o=Object.keys(a);for(let i of o)a[i]&&n[i].push(a[i])}})),n.navigate.length>0){let r=e.navigate[qi]??e.navigate,a=Ql(n.navigate,r,(...o)=>{let[i,l]=o;return{to:typeof i=="number"||typeof i=="string"?i:i?ga(i):".",...OU(e,l??{})}});a&&(a[qi]=r,e.navigate=a)}if(n.fetch.length>0){let r=e.fetch[qi]??e.fetch,a=Ql(n.fetch,r,(...o)=>{let[i,,l,u]=o;return{href:l??".",fetcherKey:i,...OU(e,u??{})}});a&&(a[qi]=r,e.fetch=a)}return e}function VTe(e,t){let n={request:[]};t.forEach(a=>a({instrument(o){let i=Object.keys(o);for(let l of i)o[l]&&n[l].push(o[l])}}));let r=e;return n.request.length>0&&(r=Ql(n.request,e,(...a)=>{let[o,i]=a;return{request:dV(o),context:i!=null?fV(i):i}})),r}function Ql(e,t,n){return e.length===0?null:async(...r)=>{let a=await uV(e,n(...r),()=>t(...r),e.length-1);if(a.type==="error")throw a.value;return a.value}}async function uV(e,t,n,r){let a=e[r],o;if(a){let i,l=async()=>(i?console.error("You cannot call instrumented handlers more than once"):i=uV(e,t,n,r-1),o=await i,Et(o,"Expected a result"),o.type==="error"&&o.value instanceof Error?{status:"error",error:o.value}:{status:"success",error:void 0});try{await a(l,t)}catch(u){console.error("An instrumentation function threw an error:",u)}i||await l(),await i}else try{o={type:"success",value:await n()}}catch(i){o={type:"error",value:i}}return o||{type:"error",value:new Error("No result assigned in instrumentation chain.")}}function IU(e){let{request:t,context:n,params:r,unstable_pattern:a}=e;return{request:dV(t),params:{...r},unstable_pattern:a,context:fV(n)}}function OU(e,t){return{currentUrl:ga(e.state.location),..."formMethod"in t?{formMethod:t.formMethod}:{},..."formEncType"in t?{formEncType:t.formEncType}:{},..."formData"in t?{formData:t.formData}:{},..."body"in t?{body:t.body}:{}}}function dV(e){return{method:e.method,url:e.url,headers:{get:(...t)=>e.headers.get(...t)}}}function fV(e){if(Qde(e)){let t={...e};return Object.freeze(t),t}else return{get:t=>e.get(t)}}var Jde=Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function Qde(e){if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null||Object.getOwnPropertyNames(t).sort().join("\0")===Jde}var pV=["POST","PUT","PATCH","DELETE"],efe=new Set(pV),tfe=["GET",...pV],nfe=new Set(tfe),mV=new Set([301,302,303,307,308]),rfe=new Set([307,308]),oy={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},QN={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},ql={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},hV=e=>({hasErrorBoundary:!!e.hasErrorBoundary}),gV="remix-router-transitions",bV=Symbol("ResetLoaderData");function eC(e){const t=e.window?e.window:typeof window<"u"?window:void 0,n=typeof t<"u"&&typeof t.document<"u"&&typeof t.document.createElement<"u";Et(e.routes.length>0,"You must provide a non-empty routes array to createRouter");let r=e.hydrationRouteProperties||[],a=e.mapRouteProperties||hV,o=a;if(e.unstable_instrumentations){let oe=e.unstable_instrumentations;o=ce=>({...a(ce),...cV(oe.map(ye=>ye.route).filter(Boolean),ce)})}let i={},l=fc(e.routes,o,void 0,i),u,f=e.basename||"/";f.startsWith("/")||(f=`/${f}`);let m=e.dataStrategy||dfe,h={...e.future},g=null,b=new Set,E=null,x=null,w=null,S=e.hydrationData!=null,_=Uo(l,e.history.location,f),T=!1,k=null,R;if(_==null&&!e.patchRoutesOnNavigation){let oe=Ar(404,{pathname:e.history.location.pathname}),{matches:ce,route:ye}=ju(l);R=!0,_=ce,k={[ye.id]:oe}}else if(_&&!e.hydrationData&&zt(_,l,e.history.location.pathname).active&&(_=null),_)if(_.some(oe=>oe.route.lazy))R=!1;else if(!_.some(oe=>tC(oe.route)))R=!0;else{let oe=e.hydrationData?e.hydrationData.loaderData:null,ce=e.hydrationData?e.hydrationData.errors:null;if(ce){let ye=_.findIndex(ke=>ce[ke.route.id]!==void 0);R=_.slice(0,ye+1).every(ke=>!p_(ke.route,oe,ce))}else R=_.every(ye=>!p_(ye.route,oe,ce))}else{R=!1,_=[];let oe=zt(null,l,e.history.location.pathname);oe.active&&oe.matches&&(T=!0,_=oe.matches)}let A,C={historyAction:e.history.action,location:e.history.location,matches:_,initialized:R,navigation:oy,restoreScrollPosition:e.hydrationData!=null?!1:null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||k,fetchers:new Map,blockers:new Map},O="POP",M=null,L=!1,j,B=!1,K=new Map,Z=null,te=!1,V=!1,Y=new Set,F=new Map,ae=0,ee=-1,P=new Map,H=new Set,U=new Map,D=new Map,$=new Set,G=new Map,W,re=null;function pe(){if(g=e.history.listen(({action:oe,location:ce,delta:ye})=>{if(W){W(),W=void 0;return}Un(G.size===0||ye!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let ke=Pt({currentLocation:C.location,nextLocation:ce,historyAction:oe});if(ke&&ye!=null){let ge=new Promise(_e=>{W=_e});e.history.go(ye*-1),jt(ke,{state:"blocked",location:ce,proceed(){jt(ke,{state:"proceeding",proceed:void 0,reset:void 0,location:ce}),ge.then(()=>e.history.go(ye))},reset(){let _e=new Map(C.blockers);_e.set(ke,ql),J({blockers:_e})}}),M?.resolve(),M=null;return}return Te(oe,ce)}),n){yfe(t,K);let oe=()=>vfe(t,K);t.addEventListener("pagehide",oe),Z=()=>t.removeEventListener("pagehide",oe)}return C.initialized||Te("POP",C.location,{initialHydration:!0}),A}function me(){g&&g(),Z&&Z(),b.clear(),j&&j.abort(),C.fetchers.forEach((oe,ce)=>ot(ce)),C.blockers.forEach((oe,ce)=>Nt(ce))}function ne(oe){return b.add(oe),()=>b.delete(oe)}function J(oe,ce={}){oe.matches&&(oe.matches=oe.matches.map(ge=>{let _e=i[ge.route.id],Ne=ge.route;return Ne.element!==_e.element||Ne.errorElement!==_e.errorElement||Ne.hydrateFallbackElement!==_e.hydrateFallbackElement?{...ge,route:_e}:ge})),C={...C,...oe};let ye=[],ke=[];C.fetchers.forEach((ge,_e)=>{ge.state==="idle"&&($.has(_e)?ye.push(_e):ke.push(_e))}),$.forEach(ge=>{!C.fetchers.has(ge)&&!F.has(ge)&&ye.push(ge)}),[...b].forEach(ge=>ge(C,{deletedFetchers:ye,newErrors:oe.errors??null,viewTransitionOpts:ce.viewTransitionOpts,flushSync:ce.flushSync===!0})),ye.forEach(ge=>ot(ge)),ke.forEach(ge=>C.fetchers.delete(ge))}function X(oe,ce,{flushSync:ye}={}){let ke=C.actionData!=null&&C.navigation.formMethod!=null&&Zr(C.navigation.formMethod)&&C.navigation.state==="loading"&&oe.state?._isRedirect!==!0,ge;ce.actionData?Object.keys(ce.actionData).length>0?ge=ce.actionData:ge=null:ke?ge=C.actionData:ge=null;let _e=ce.loaderData?VU(C.loaderData,ce.loaderData,ce.matches||[],ce.errors):C.loaderData,Ne=C.blockers;Ne.size>0&&(Ne=new Map(Ne),Ne.forEach((qe,et)=>Ne.set(et,ql)));let Ae=te?!1:Ht(oe,ce.matches||C.matches),Pe=L===!0||C.navigation.formMethod!=null&&Zr(C.navigation.formMethod)&&oe.state?._isRedirect!==!0;u&&(l=u,u=void 0),te||O==="POP"||(O==="PUSH"?e.history.push(oe,oe.state):O==="REPLACE"&&e.history.replace(oe,oe.state));let Ze;if(O==="POP"){let qe=K.get(C.location.pathname);qe&&qe.has(oe.pathname)?Ze={currentLocation:C.location,nextLocation:oe}:K.has(oe.pathname)&&(Ze={currentLocation:oe,nextLocation:C.location})}else if(B){let qe=K.get(C.location.pathname);qe?qe.add(oe.pathname):(qe=new Set([oe.pathname]),K.set(C.location.pathname,qe)),Ze={currentLocation:C.location,nextLocation:oe}}J({...ce,actionData:ge,loaderData:_e,historyAction:O,location:oe,initialized:!0,navigation:oy,revalidation:"idle",restoreScrollPosition:Ae,preventScrollReset:Pe,blockers:Ne},{viewTransitionOpts:Ze,flushSync:ye===!0}),O="POP",L=!1,B=!1,te=!1,V=!1,M?.resolve(),M=null,re?.resolve(),re=null}async function se(oe,ce){if(M?.resolve(),M=null,typeof oe=="number"){M||(M=KU());let tt=M.promise;return e.history.go(oe),tt}let ye=f_(C.location,C.matches,f,oe,ce?.fromRouteId,ce?.relative),{path:ke,submission:ge,error:_e}=LU(!1,ye,ce),Ne=C.location,Ae=ri(C.location,ke,ce&&ce.state);Ae={...Ae,...e.history.encodeLocation(Ae)};let Pe=ce&&ce.replace!=null?ce.replace:void 0,Ze="PUSH";Pe===!0?Ze="REPLACE":Pe===!1||ge!=null&&Zr(ge.formMethod)&&ge.formAction===C.location.pathname+C.location.search&&(Ze="REPLACE");let qe=ce&&"preventScrollReset"in ce?ce.preventScrollReset===!0:void 0,et=(ce&&ce.flushSync)===!0,Ut=Pt({currentLocation:Ne,nextLocation:Ae,historyAction:Ze});if(Ut){jt(Ut,{state:"blocked",location:Ae,proceed(){jt(Ut,{state:"proceeding",proceed:void 0,reset:void 0,location:Ae}),se(oe,ce)},reset(){let tt=new Map(C.blockers);tt.set(Ut,ql),J({blockers:tt})}});return}await Te(Ze,Ae,{submission:ge,pendingError:_e,preventScrollReset:qe,replace:ce&&ce.replace,enableViewTransition:ce&&ce.viewTransition,flushSync:et,callSiteDefaultShouldRevalidate:ce&&ce.unstable_defaultShouldRevalidate})}function he(){re||(re=KU()),st(),J({revalidation:"loading"});let oe=re.promise;return C.navigation.state==="submitting"?oe:C.navigation.state==="idle"?(Te(C.historyAction,C.location,{startUninterruptedRevalidation:!0}),oe):(Te(O||C.historyAction,C.navigation.location,{overrideNavigation:C.navigation,enableViewTransition:B===!0}),oe)}async function Te(oe,ce,ye){j&&j.abort(),j=null,O=oe,te=(ye&&ye.startUninterruptedRevalidation)===!0,$t(C.location,C.matches),L=(ye&&ye.preventScrollReset)===!0,B=(ye&&ye.enableViewTransition)===!0;let ke=u||l,ge=ye&&ye.overrideNavigation,_e=ye?.initialHydration&&C.matches&&C.matches.length>0&&!T?C.matches:Uo(ke,ce,f),Ne=(ye&&ye.flushSync)===!0;if(_e&&C.initialized&&!V&&pfe(C.location,ce)&&!(ye&&ye.submission&&Zr(ye.submission.formMethod))){X(ce,{matches:_e},{flushSync:Ne});return}let Ae=zt(_e,ke,ce.pathname);if(Ae.active&&Ae.matches&&(_e=Ae.matches),!_e){let{error:Ct,notFoundMatches:Qe,route:Ke}=Xt(ce.pathname);X(ce,{matches:Qe,loaderData:{},errors:{[Ke.id]:Ct}},{flushSync:Ne});return}j=new AbortController;let Pe=Su(e.history,ce,j.signal,ye&&ye.submission),Ze=e.getContext?await e.getContext():new Mu,qe;if(ye&&ye.pendingError)qe=[wo(_e).route.id,{type:"error",error:ye.pendingError}];else if(ye&&ye.submission&&Zr(ye.submission.formMethod)){let Ct=await Be(Pe,ce,ye.submission,_e,Ze,Ae.active,ye&&ye.initialHydration===!0,{replace:ye.replace,flushSync:Ne});if(Ct.shortCircuited)return;if(Ct.pendingActionResult){let[Qe,Ke]=Ct.pendingActionResult;if(zr(Ke)&&So(Ke.error)&&Ke.error.status===404){j=null,X(ce,{matches:Ct.matches,loaderData:{},errors:{[Qe]:Ke.error}});return}}_e=Ct.matches||_e,qe=Ct.pendingActionResult,ge=UE(ce,ye.submission),Ne=!1,Ae.active=!1,Pe=Su(e.history,Pe.url,Pe.signal)}let{shortCircuited:et,matches:Ut,loaderData:tt,errors:xt}=await $e(Pe,ce,_e,Ze,Ae.active,ge,ye&&ye.submission,ye&&ye.fetcherSubmission,ye&&ye.replace,ye&&ye.initialHydration===!0,Ne,qe,ye&&ye.callSiteDefaultShouldRevalidate);et||(j=null,X(ce,{matches:Ut||_e,...GU(qe),loaderData:tt,errors:xt}))}async function Be(oe,ce,ye,ke,ge,_e,Ne,Ae={}){st();let Pe=gfe(ce,ye);if(J({navigation:Pe},{flushSync:Ae.flushSync===!0}),_e){let et=await Ln(ke,ce.pathname,oe.signal);if(et.type==="aborted")return{shortCircuited:!0};if(et.type==="error"){if(et.partialMatches.length===0){let{matches:tt,route:xt}=ju(l);return{matches:tt,pendingActionResult:[xt.id,{type:"error",error:et.error}]}}let Ut=wo(et.partialMatches).route.id;return{matches:et.partialMatches,pendingActionResult:[Ut,{type:"error",error:et.error}]}}else if(et.matches)ke=et.matches;else{let{notFoundMatches:Ut,error:tt,route:xt}=Xt(ce.pathname);return{matches:Ut,pendingActionResult:[xt.id,{type:"error",error:tt}]}}}let Ze,qe=Ju(ke,ce);if(!qe.route.action&&!qe.route.lazy)Ze={type:"error",error:Ar(405,{method:oe.method,pathname:ce.pathname,routeId:qe.route.id})};else{let et=el(o,i,oe,ke,qe,Ne?[]:r,ge),Ut=await Ce(oe,et,ge,null);if(Ze=Ut[qe.route.id],!Ze){for(let tt of ke)if(Ut[tt.route.id]){Ze=Ut[tt.route.id];break}}if(oe.signal.aborted)return{shortCircuited:!0}}if(Xi(Ze)){let et;return Ae&&Ae.replace!=null?et=Ae.replace:et=FU(Ze.response.headers.get("Location"),new URL(oe.url),f,e.history)===C.location.pathname+C.location.search,await Ee(oe,Ze,!0,{submission:ye,replace:et}),{shortCircuited:!0}}if(zr(Ze)){let et=wo(ke,qe.route.id);return(Ae&&Ae.replace)!==!0&&(O="PUSH"),{matches:ke,pendingActionResult:[et.route.id,Ze,qe.route.id]}}return{matches:ke,pendingActionResult:[qe.route.id,Ze]}}async function $e(oe,ce,ye,ke,ge,_e,Ne,Ae,Pe,Ze,qe,et,Ut){let tt=_e||UE(ce,Ne),xt=Ne||Ae||WU(tt),Ct=!te&&!Ze;if(ge){if(Ct){let Rt=Ge(et);J({navigation:tt,...Rt!==void 0?{actionData:Rt}:{}},{flushSync:qe})}let Ft=await Ln(ye,ce.pathname,oe.signal);if(Ft.type==="aborted")return{shortCircuited:!0};if(Ft.type==="error"){if(Ft.partialMatches.length===0){let{matches:xr,route:Wn}=ju(l);return{matches:xr,loaderData:{},errors:{[Wn.id]:Ft.error}}}let Rt=wo(Ft.partialMatches).route.id;return{matches:Ft.partialMatches,loaderData:{},errors:{[Rt]:Ft.error}}}else if(Ft.matches)ye=Ft.matches;else{let{error:Rt,notFoundMatches:xr,route:Wn}=Xt(ce.pathname);return{matches:xr,loaderData:{},errors:{[Wn.id]:Rt}}}}let Qe=u||l,{dsMatches:Ke,revalidatingFetchers:St}=MU(oe,ke,o,i,e.history,C,ye,xt,ce,Ze?[]:r,Ze===!0,V,Y,$,U,H,Qe,f,e.patchRoutesOnNavigation!=null,et,Ut);if(ee=++ae,!e.dataStrategy&&!Ke.some(Ft=>Ft.shouldLoad)&&!Ke.some(Ft=>Ft.route.middleware&&Ft.route.middleware.length>0)&&St.length===0){let Ft=We();return X(ce,{matches:ye,loaderData:{},errors:et&&zr(et[1])?{[et[0]]:et[1].error}:null,...GU(et),...Ft?{fetchers:new Map(C.fetchers)}:{}},{flushSync:qe}),{shortCircuited:!0}}if(Ct){let Ft={};if(!ge){Ft.navigation=tt;let Rt=Ge(et);Rt!==void 0&&(Ft.actionData=Rt)}St.length>0&&(Ft.fetchers=dt(St)),J(Ft,{flushSync:qe})}St.forEach(Ft=>{qt(Ft.key),Ft.controller&&F.set(Ft.key,Ft.controller)});let En=()=>St.forEach(Ft=>qt(Ft.key));j&&j.signal.addEventListener("abort",En);let{loaderResults:ht,fetcherResults:Fn}=await He(Ke,St,oe,ke);if(oe.signal.aborted)return{shortCircuited:!0};j&&j.signal.removeEventListener("abort",En),St.forEach(Ft=>F.delete(Ft.key));let _t=Ab(ht);if(_t)return await Ee(oe,_t.result,!0,{replace:Pe}),{shortCircuited:!0};if(_t=Ab(Fn),_t)return H.add(_t.key),await Ee(oe,_t.result,!0,{replace:Pe}),{shortCircuited:!0};let{loaderData:Cn,errors:en}=HU(C,ye,ht,et,St,Fn);Ze&&C.errors&&(en={...C.errors,...en});let bn=We(),Xn=ue(ee),cr=bn||Xn||St.length>0;return{matches:ye,loaderData:Cn,errors:en,...cr?{fetchers:new Map(C.fetchers)}:{}}}function Ge(oe){if(oe&&!zr(oe[1]))return{[oe[0]]:oe[1].data};if(C.actionData)return Object.keys(C.actionData).length===0?null:C.actionData}function dt(oe){return oe.forEach(ce=>{let ye=C.fetchers.get(ce.key),ke=bp(void 0,ye?ye.data:void 0);C.fetchers.set(ce.key,ke)}),new Map(C.fetchers)}async function Ve(oe,ce,ye,ke){qt(oe);let ge=(ke&&ke.flushSync)===!0,_e=u||l,Ne=f_(C.location,C.matches,f,ye,ce,ke?.relative),Ae=Uo(_e,Ne,f),Pe=zt(Ae,_e,Ne);if(Pe.active&&Pe.matches&&(Ae=Pe.matches),!Ae){it(oe,ce,Ar(404,{pathname:Ne}),{flushSync:ge});return}let{path:Ze,submission:qe,error:et}=LU(!0,Ne,ke);if(et){it(oe,ce,et,{flushSync:ge});return}let Ut=e.getContext?await e.getContext():new Mu,tt=(ke&&ke.preventScrollReset)===!0;if(qe&&Zr(qe.formMethod)){await ct(oe,ce,Ze,Ae,Ut,Pe.active,ge,tt,qe,ke&&ke.unstable_defaultShouldRevalidate);return}U.set(oe,{routeId:ce,path:Ze}),await rt(oe,ce,Ze,Ae,Ut,Pe.active,ge,tt,qe)}async function ct(oe,ce,ye,ke,ge,_e,Ne,Ae,Pe,Ze){st(),U.delete(oe);let qe=C.fetchers.get(oe);Je(oe,bfe(Pe,qe),{flushSync:Ne});let et=new AbortController,Ut=Su(e.history,ye,et.signal,Pe);if(_e){let nn=await Ln(ke,new URL(Ut.url).pathname,Ut.signal,oe);if(nn.type==="aborted")return;if(nn.type==="error"){it(oe,ce,nn.error,{flushSync:Ne});return}else if(nn.matches)ke=nn.matches;else{it(oe,ce,Ar(404,{pathname:ye}),{flushSync:Ne});return}}let tt=Ju(ke,ye);if(!tt.route.action&&!tt.route.lazy){let nn=Ar(405,{method:Pe.formMethod,pathname:ye,routeId:ce});it(oe,ce,nn,{flushSync:Ne});return}F.set(oe,et);let xt=ae,Ct=el(o,i,Ut,ke,tt,r,ge),Qe=await Ce(Ut,Ct,ge,oe),Ke=Qe[tt.route.id];if(!Ke){for(let nn of Ct)if(Qe[nn.route.id]){Ke=Qe[nn.route.id];break}}if(Ut.signal.aborted){F.get(oe)===et&&F.delete(oe);return}if($.has(oe)){if(Xi(Ke)||zr(Ke)){Je(oe,Gs(void 0));return}}else{if(Xi(Ke))if(F.delete(oe),ee>xt){Je(oe,Gs(void 0));return}else return H.add(oe),Je(oe,bp(Pe)),Ee(Ut,Ke,!1,{fetcherSubmission:Pe,preventScrollReset:Ae});if(zr(Ke)){it(oe,ce,Ke.error);return}}let St=C.navigation.location||C.location,En=Su(e.history,St,et.signal),ht=u||l,Fn=C.navigation.state!=="idle"?Uo(ht,C.navigation.location,f):C.matches;Et(Fn,"Didn't find any matches after fetcher action");let _t=++ae;P.set(oe,_t);let Cn=bp(Pe,Ke.data);C.fetchers.set(oe,Cn);let{dsMatches:en,revalidatingFetchers:bn}=MU(En,ge,o,i,e.history,C,Fn,Pe,St,r,!1,V,Y,$,U,H,ht,f,e.patchRoutesOnNavigation!=null,[tt.route.id,Ke],Ze);bn.filter(nn=>nn.key!==oe).forEach(nn=>{let va=nn.key,Oc=C.fetchers.get(va),ui=bp(void 0,Oc?Oc.data:void 0);C.fetchers.set(va,ui),qt(va),nn.controller&&F.set(va,nn.controller)}),J({fetchers:new Map(C.fetchers)});let Xn=()=>bn.forEach(nn=>qt(nn.key));et.signal.addEventListener("abort",Xn);let{loaderResults:cr,fetcherResults:Ft}=await He(en,bn,En,ge);if(et.signal.aborted)return;if(et.signal.removeEventListener("abort",Xn),P.delete(oe),F.delete(oe),bn.forEach(nn=>F.delete(nn.key)),C.fetchers.has(oe)){let nn=Gs(Ke.data);C.fetchers.set(oe,nn)}let Rt=Ab(cr);if(Rt)return Ee(En,Rt.result,!1,{preventScrollReset:Ae});if(Rt=Ab(Ft),Rt)return H.add(Rt.key),Ee(En,Rt.result,!1,{preventScrollReset:Ae});let{loaderData:xr,errors:Wn}=HU(C,Fn,cr,void 0,bn,Ft);ue(_t),C.navigation.state==="loading"&&_t>ee?(Et(O,"Expected pending action"),j&&j.abort(),X(C.navigation.location,{matches:Fn,loaderData:xr,errors:Wn,fetchers:new Map(C.fetchers)})):(J({errors:Wn,loaderData:VU(C.loaderData,xr,Fn,Wn),fetchers:new Map(C.fetchers)}),V=!1)}async function rt(oe,ce,ye,ke,ge,_e,Ne,Ae,Pe){let Ze=C.fetchers.get(oe);Je(oe,bp(Pe,Ze?Ze.data:void 0),{flushSync:Ne});let qe=new AbortController,et=Su(e.history,ye,qe.signal);if(_e){let Ke=await Ln(ke,new URL(et.url).pathname,et.signal,oe);if(Ke.type==="aborted")return;if(Ke.type==="error"){it(oe,ce,Ke.error,{flushSync:Ne});return}else if(Ke.matches)ke=Ke.matches;else{it(oe,ce,Ar(404,{pathname:ye}),{flushSync:Ne});return}}let Ut=Ju(ke,ye);F.set(oe,qe);let tt=ae,xt=el(o,i,et,ke,Ut,r,ge),Qe=(await Ce(et,xt,ge,oe))[Ut.route.id];if(F.get(oe)===qe&&F.delete(oe),!et.signal.aborted){if($.has(oe)){Je(oe,Gs(void 0));return}if(Xi(Qe))if(ee>tt){Je(oe,Gs(void 0));return}else{H.add(oe),await Ee(et,Qe,!1,{preventScrollReset:Ae});return}if(zr(Qe)){it(oe,ce,Qe.error);return}Je(oe,Gs(Qe.data))}}async function Ee(oe,ce,ye,{submission:ke,fetcherSubmission:ge,preventScrollReset:_e,replace:Ne}={}){ye||(M?.resolve(),M=null),ce.response.headers.has("X-Remix-Revalidate")&&(V=!0);let Ae=ce.response.headers.get("Location");Et(Ae,"Expected a Location header on the redirect Response"),Ae=FU(Ae,new URL(oe.url),f,e.history);let Pe=ri(C.location,Ae,{_isRedirect:!0});if(n){let xt=!1;if(ce.response.headers.has("X-Remix-Reload-Document"))xt=!0;else if(rw(Ae)){const Ct=QH(Ae,!0);xt=Ct.origin!==t.location.origin||Na(Ct.pathname,f)==null}if(xt){Ne?t.location.replace(Ae):t.location.assign(Ae);return}}j=null;let Ze=Ne===!0||ce.response.headers.has("X-Remix-Replace")?"REPLACE":"PUSH",{formMethod:qe,formAction:et,formEncType:Ut}=C.navigation;!ke&&!ge&&qe&&et&&Ut&&(ke=WU(C.navigation));let tt=ke||ge;if(rfe.has(ce.response.status)&&tt&&Zr(tt.formMethod))await Te(Ze,Pe,{submission:{...tt,formAction:Ae},preventScrollReset:_e||L,enableViewTransition:ye?B:void 0});else{let xt=UE(Pe,ke);await Te(Ze,Pe,{overrideNavigation:xt,fetcherSubmission:ge,preventScrollReset:_e||L,enableViewTransition:ye?B:void 0})}}async function Ce(oe,ce,ye,ke){let ge,_e={};try{ge=await SV(m,oe,ce,ke,ye,!1)}catch(Ne){return ce.filter(Ae=>Ae.shouldLoad).forEach(Ae=>{_e[Ae.route.id]={type:"error",error:Ne}}),_e}if(oe.signal.aborted)return _e;if(!Zr(oe.method))for(let Ne of ce){if(ge[Ne.route.id]?.type==="error")break;!ge.hasOwnProperty(Ne.route.id)&&!C.loaderData.hasOwnProperty(Ne.route.id)&&(!C.errors||!C.errors.hasOwnProperty(Ne.route.id))&&Ne.shouldCallHandler()&&(ge[Ne.route.id]={type:"error",result:new Error(`No result returned from dataStrategy for route ${Ne.route.id}`)})}for(let[Ne,Ae]of Object.entries(ge))if(IV(Ae)){let Pe=Ae.result;_e[Ne]={type:"redirect",response:NV(Pe,oe,Ne,ce,f)}}else _e[Ne]=await TV(Ae);return _e}async function He(oe,ce,ye,ke){let ge=Ce(ye,oe,ke,null),_e=Promise.all(ce.map(async Pe=>{if(Pe.matches&&Pe.match&&Pe.request&&Pe.controller){let qe=(await Ce(Pe.request,Pe.matches,ke,Pe.key))[Pe.match.route.id];return{[Pe.key]:qe}}else return Promise.resolve({[Pe.key]:{type:"error",error:Ar(404,{pathname:Pe.path})}})})),Ne=await ge,Ae=(await _e).reduce((Pe,Ze)=>Object.assign(Pe,Ze),{});return{loaderResults:Ne,fetcherResults:Ae}}function st(){V=!0,U.forEach((oe,ce)=>{F.has(ce)&&Y.add(ce),qt(ce)})}function Je(oe,ce,ye={}){C.fetchers.set(oe,ce),J({fetchers:new Map(C.fetchers)},{flushSync:(ye&&ye.flushSync)===!0})}function it(oe,ce,ye,ke={}){let ge=wo(C.matches,ce);ot(oe),J({errors:{[ge.route.id]:ye},fetchers:new Map(C.fetchers)},{flushSync:(ke&&ke.flushSync)===!0})}function kt(oe){return D.set(oe,(D.get(oe)||0)+1),$.has(oe)&&$.delete(oe),C.fetchers.get(oe)||QN}function Nn(oe,ce){qt(oe,ce?.reason),Je(oe,Gs(null))}function ot(oe){let ce=C.fetchers.get(oe);F.has(oe)&&!(ce&&ce.state==="loading"&&P.has(oe))&&qt(oe),U.delete(oe),P.delete(oe),H.delete(oe),$.delete(oe),Y.delete(oe),C.fetchers.delete(oe)}function zn(oe){let ce=(D.get(oe)||0)-1;ce<=0?(D.delete(oe),$.add(oe)):D.set(oe,ce),J({fetchers:new Map(C.fetchers)})}function qt(oe,ce){let ye=F.get(oe);ye&&(ye.abort(ce),F.delete(oe))}function Ye(oe){for(let ce of oe){let ye=kt(ce),ke=Gs(ye.data);C.fetchers.set(ce,ke)}}function We(){let oe=[],ce=!1;for(let ye of H){let ke=C.fetchers.get(ye);Et(ke,`Expected fetcher: ${ye}`),ke.state==="loading"&&(H.delete(ye),oe.push(ye),ce=!0)}return Ye(oe),ce}function ue(oe){let ce=[];for(let[ye,ke]of P)if(ke<oe){let ge=C.fetchers.get(ye);Et(ge,`Expected fetcher: ${ye}`),ge.state==="loading"&&(qt(ye),P.delete(ye),ce.push(ye))}return Ye(ce),ce.length>0}function It(oe,ce){let ye=C.blockers.get(oe)||ql;return G.get(oe)!==ce&&G.set(oe,ce),ye}function Nt(oe){C.blockers.delete(oe),G.delete(oe)}function jt(oe,ce){let ye=C.blockers.get(oe)||ql;Et(ye.state==="unblocked"&&ce.state==="blocked"||ye.state==="blocked"&&ce.state==="blocked"||ye.state==="blocked"&&ce.state==="proceeding"||ye.state==="blocked"&&ce.state==="unblocked"||ye.state==="proceeding"&&ce.state==="unblocked",`Invalid blocker state transition: ${ye.state} -> ${ce.state}`);let ke=new Map(C.blockers);ke.set(oe,ce),J({blockers:ke})}function Pt({currentLocation:oe,nextLocation:ce,historyAction:ye}){if(G.size===0)return;G.size>1&&Un(!1,"A router only supports one blocker at a time");let ke=Array.from(G.entries()),[ge,_e]=ke[ke.length-1],Ne=C.blockers.get(ge);if(!(Ne&&Ne.state==="proceeding")&&_e({currentLocation:oe,nextLocation:ce,historyAction:ye}))return ge}function Xt(oe){let ce=Ar(404,{pathname:oe}),ye=u||l,{matches:ke,route:ge}=ju(ye);return{notFoundMatches:ke,route:ge,error:ce}}function xn(oe,ce,ye){if(E=oe,w=ce,x=ye||null,!S&&C.navigation===oy){S=!0;let ke=Ht(C.location,C.matches);ke!=null&&J({restoreScrollPosition:ke})}return()=>{E=null,w=null,x=null}}function ut(oe,ce){return x&&x(oe,ce.map(ke=>eV(ke,C.loaderData)))||oe.key}function $t(oe,ce){if(E&&w){let ye=ut(oe,ce);E[ye]=w()}}function Ht(oe,ce){if(E){let ye=ut(oe,ce),ke=E[ye];if(typeof ke=="number")return ke}return null}function zt(oe,ce,ye){if(e.patchRoutesOnNavigation)if(oe){if(Object.keys(oe[0].params).length>0)return{active:!0,matches:Rp(ce,ye,f,!0)}}else return{active:!0,matches:Rp(ce,ye,f,!0)||[]};return{active:!1,matches:null}}async function Ln(oe,ce,ye,ke){if(!e.patchRoutesOnNavigation)return{type:"success",matches:oe};let ge=oe;for(;;){let _e=u==null,Ne=u||l,Ae=i;try{await e.patchRoutesOnNavigation({signal:ye,path:ce,matches:ge,fetcherKey:ke,patch:(qe,et)=>{ye.aborted||jU(qe,et,Ne,Ae,o,!1)}})}catch(qe){return{type:"error",error:qe,partialMatches:ge}}finally{_e&&!ye.aborted&&(l=[...l])}if(ye.aborted)return{type:"aborted"};let Pe=Uo(Ne,ce,f),Ze=null;if(Pe){if(Object.keys(Pe[0].params).length===0)return{type:"success",matches:Pe};if(Ze=Rp(Ne,ce,f,!0),!(Ze&&ge.length<Ze.length&&sn(ge,Ze.slice(0,ge.length))))return{type:"success",matches:Pe}}if(Ze||(Ze=Rp(Ne,ce,f,!0)),!Ze||sn(ge,Ze))return{type:"success",matches:null};ge=Ze}}function sn(oe,ce){return oe.length===ce.length&&oe.every((ye,ke)=>ye.route.id===ce[ke].route.id)}function Mn(oe){i={},u=fc(oe,o,void 0,i)}function qn(oe,ce,ye=!1){let ke=u==null;jU(oe,ce,u||l,i,o,ye),ke&&(l=[...l],J({}))}return A={get basename(){return f},get future(){return h},get state(){return C},get routes(){return l},get window(){return t},initialize:pe,subscribe:ne,enableScrollRestoration:xn,navigate:se,fetch:Ve,revalidate:he,createHref:oe=>e.history.createHref(oe),encodeLocation:oe=>e.history.encodeLocation(oe),getFetcher:kt,resetFetcher:Nn,deleteFetcher:zn,dispose:me,getBlocker:It,deleteBlocker:Nt,patchRoutes:qn,_internalFetchControllers:F,_internalSetRoutes:Mn,_internalSetStateDoNotUseOrYouWillBreakYourApp(oe){J(oe)}},e.unstable_instrumentations&&(A=Xde(A,e.unstable_instrumentations.map(oe=>oe.router).filter(Boolean))),A}function afe(e,t){Et(e.length>0,"You must provide a non-empty routes array to createStaticHandler");let n={},r=(t?t.basename:null)||"/",a=t?.mapRouteProperties||hV,o=a;if(t?.unstable_instrumentations){let b=t.unstable_instrumentations;o=E=>({...a(E),...cV(b.map(x=>x.route).filter(Boolean),E)})}let i=fc(e,o,void 0,n);async function l(b,{requestContext:E,filterMatchesToLoad:x,skipLoaderErrorBubbling:w,skipRevalidation:S,dataStrategy:_,generateMiddlewareResponse:T}={}){let k=new URL(b.url),R=b.method,A=ri("",ga(k),null,"default"),C=Uo(i,A,r);if(E=E??new Mu,!y_(R)&&R!=="HEAD"){let M=Ar(405,{method:R}),{matches:L,route:j}=ju(i),B={basename:r,location:A,matches:L,loaderData:{},actionData:null,errors:{[j.id]:M},statusCode:M.status,loaderHeaders:{},actionHeaders:{}};return T?T(()=>Promise.resolve(B)):B}else if(!C){let M=Ar(404,{pathname:A.pathname}),{matches:L,route:j}=ju(i),B={basename:r,location:A,matches:L,loaderData:{},actionData:null,errors:{[j.id]:M},statusCode:M.status,loaderHeaders:{},actionHeaders:{}};return T?T(()=>Promise.resolve(B)):B}if(T){Et(E instanceof Mu,"When using middleware in `staticHandler.query()`, any provided `requestContext` must be an instance of `RouterContextProvider`");try{await UU(C,n,o);let M,L=await zU({request:b,unstable_pattern:Ys(C),matches:C,params:C[0].params,context:E},async()=>await T(async(B,K={})=>{let Z=await f(B,A,C,E,_||null,w===!0,null,"filterMatchesToLoad"in K?K.filterMatchesToLoad??null:x??null,S===!0);return ua(Z)?Z:(M={location:A,basename:r,...Z},M)}),async(j,B)=>{if(b_(j))return j;if(ua(j))try{j=new ws(j.status,j.statusText,await _V(j))}catch(K){j=K}if(ac(j)&&(j=kV(j)),M){B in M.loaderData&&(M.loaderData[B]=void 0);let K=ofe(i,M,j,w?B:wo(C,B).route.id);return T(()=>Promise.resolve(K))}else{let K=w?B:wo(C,C.find(te=>te.route.id===B||te.route.loader)?.route.id||B).route.id,Z={matches:C,location:A,basename:r,loaderData:{},actionData:null,errors:{[K]:j},statusCode:So(j)?j.status:500,actionHeaders:{},loaderHeaders:{}};return T(()=>Promise.resolve(Z))}});return Et(ua(L),"Expected a response in query()"),L}catch(M){if(ua(M))return M;throw M}}let O=await f(b,A,C,E,_||null,w===!0,null,x||null,S===!0);return ua(O)?O:{location:A,basename:r,...O}}async function u(b,{routeId:E,requestContext:x,dataStrategy:w,generateMiddlewareResponse:S}={}){let _=new URL(b.url),T=b.method,k=ri("",ga(_),null,"default"),R=Uo(i,k,r);if(x=x??new Mu,!y_(T)&&T!=="HEAD"&&T!=="OPTIONS")throw Ar(405,{method:T});if(!R)throw Ar(404,{pathname:k.pathname});let A=E?R.find(M=>M.route.id===E):Ju(R,k);if(E&&!A)throw Ar(403,{pathname:k.pathname,routeId:E});if(!A)throw Ar(404,{pathname:k.pathname});if(S)return Et(x instanceof Mu,"When using middleware in `staticHandler.queryRoute()`, any provided `requestContext` must be an instance of `RouterContextProvider`"),await UU(R,n,o),await zU({request:b,unstable_pattern:Ys(R),matches:R,params:R[0].params,context:x},async()=>await S(async j=>{let B=await f(j,k,R,x,w||null,!1,A,null,!1),K=O(B);return ua(K)?K:typeof K=="string"?new Response(K):Response.json(K)}),L=>{if(ac(L))return Promise.resolve(g_(L));if(ua(L))return Promise.resolve(L);throw L});let C=await f(b,k,R,x,w||null,!1,A,null,!1);return O(C);function O(M){if(ua(M))return M;let L=M.errors?Object.values(M.errors)[0]:void 0;if(L!==void 0)throw L;if(M.actionData)return Object.values(M.actionData)[0];if(M.loaderData)return Object.values(M.loaderData)[0]}}async function f(b,E,x,w,S,_,T,k,R){Et(b.signal,"query()/queryRoute() requests must contain an AbortController signal");try{if(Zr(b.method))return await m(b,x,T||Ju(x,E),w,S,_,T!=null,k,R);let A=await h(b,x,w,S,_,T,k);return ua(A)?A:{...A,actionData:null,actionHeaders:{}}}catch(A){if(AV(A)&&ua(A.result)){if(A.type==="error")throw A.result;return A.result}if(b_(A))return A;throw A}}async function m(b,E,x,w,S,_,T,k,R){let A;if(!x.route.action&&!x.route.lazy){let M=Ar(405,{method:b.method,pathname:new URL(b.url).pathname,routeId:x.route.id});if(T)throw M;A={type:"error",error:M}}else{let M=el(o,n,b,E,x,[],w);A=(await g(b,M,T,w,S))[x.route.id],b.signal.aborted&&DU(b,T)}if(Xi(A))throw new Response(null,{status:A.response.status,headers:{Location:A.response.headers.get("Location")}});if(T){if(zr(A))throw A.error;return{matches:[x],loaderData:{},actionData:{[x.route.id]:A.data},errors:null,statusCode:200,loaderHeaders:{},actionHeaders:{}}}if(R)if(zr(A)){let M=_?x:wo(E,x.route.id);return{statusCode:So(A.error)?A.error.status:A.statusCode!=null?A.statusCode:500,actionData:null,actionHeaders:{...A.headers?{[x.route.id]:A.headers}:{}},matches:E,loaderData:{},errors:{[M.route.id]:A.error},loaderHeaders:{}}}else return{actionData:{[x.route.id]:A.data},actionHeaders:A.headers?{[x.route.id]:A.headers}:{},matches:E,loaderData:{},errors:null,statusCode:A.statusCode||200,loaderHeaders:{}};let C=new Request(b.url,{headers:b.headers,redirect:b.redirect,signal:b.signal});if(zr(A)){let M=_?x:wo(E,x.route.id);return{...await h(C,E,w,S,_,null,k,[M.route.id,A]),statusCode:So(A.error)?A.error.status:A.statusCode!=null?A.statusCode:500,actionData:null,actionHeaders:{...A.headers?{[x.route.id]:A.headers}:{}}}}return{...await h(C,E,w,S,_,null,k),actionData:{[x.route.id]:A.data},...A.statusCode?{statusCode:A.statusCode}:{},actionHeaders:A.headers?{[x.route.id]:A.headers}:{}}}async function h(b,E,x,w,S,_,T,k){let R=_!=null;if(R&&!_?.route.loader&&!_?.route.lazy)throw Ar(400,{method:b.method,pathname:new URL(b.url).pathname,routeId:_?.route.id});let A;if(_)A=el(o,n,b,E,_,[],x);else{let M=k&&zr(k[1])?E.findIndex(j=>j.route.id===k[0])-1:void 0,L=Ys(E);A=E.map((j,B)=>M!=null&&B>M?bm(o,n,b,L,j,[],x,!1):bm(o,n,b,L,j,[],x,(j.route.loader||j.route.lazy)!=null&&(!T||T(j))))}if(!w&&!A.some(M=>M.shouldLoad))return{matches:E,loaderData:{},errors:k&&zr(k[1])?{[k[0]]:k[1].error}:null,statusCode:200,loaderHeaders:{}};let C=await g(b,A,R,x,w);return b.signal.aborted&&DU(b,R),{...CV(E,C,k,!0,S),matches:E}}async function g(b,E,x,w,S){let _=await SV(S||m_,b,E,null,w,!0),T={};return await Promise.all(E.map(async k=>{if(!(k.route.id in _))return;let R=_[k.route.id];if(IV(R)){let A=R.result;throw NV(A,b,k.route.id,E,r)}if(x){if(ua(R.result))throw R;if(ac(R.result))throw g_(R.result)}T[k.route.id]=await TV(R)})),T}return{dataRoutes:i,query:l,queryRoute:u}}function ofe(e,t,n,r){let a=r||t._deepestRenderedBoundaryId||e[0].id;return{...t,statusCode:So(n)?n.status:500,errors:{[a]:n}}}function DU(e,t){if(e.signal.reason!==void 0)throw e.signal.reason;let n=t?"queryRoute":"query";throw new Error(`${n}() call aborted without an \`AbortSignal.reason\`: ${e.method} ${e.url}`)}function sfe(e){return e!=null&&("formData"in e&&e.formData!=null||"body"in e&&e.body!==void 0)}function f_(e,t,n,r,a,o){let i,l;if(a){i=[];for(let f of t)if(i.push(f),f.route.id===a){l=f;break}}else i=t,l=t[t.length-1];let u=ow(r||".",aw(i),Na(e.pathname,n)||e.pathname,o==="path");if(r==null&&(u.search=e.search,u.hash=e.hash),(r==null||r===""||r===".")&&l){let f=rC(u.search);if(l.route.index&&!f)u.search=u.search?u.search.replace(/^\?/,"?index&"):"?index";else if(!l.route.index&&f){let m=new URLSearchParams(u.search),h=m.getAll("index");m.delete("index"),h.filter(b=>b).forEach(b=>m.append("index",b));let g=m.toString();u.search=g?`?${g}`:""}}return n!=="/"&&(u.pathname=Vde({basename:n,pathname:u.pathname})),ga(u)}function LU(e,t,n){if(!n||!sfe(n))return{path:t};if(n.formMethod&&!y_(n.formMethod))return{path:t,error:Ar(405,{method:n.formMethod})};let r=()=>({path:t,error:Ar(400,{type:"invalid-body"})}),o=(n.formMethod||"get").toUpperCase(),i=RV(t);if(n.body!==void 0){if(n.formEncType==="text/plain"){if(!Zr(o))return r();let h=typeof n.body=="string"?n.body:n.body instanceof FormData||n.body instanceof URLSearchParams?Array.from(n.body.entries()).reduce((g,[b,E])=>`${g}${b}=${E}
92
92
  `,""):String(n.body);return{path:t,submission:{formMethod:o,formAction:i,formEncType:n.formEncType,formData:void 0,json:void 0,text:h}}}else if(n.formEncType==="application/json"){if(!Zr(o))return r();try{let h=typeof n.body=="string"?JSON.parse(n.body):n.body;return{path:t,submission:{formMethod:o,formAction:i,formEncType:n.formEncType,formData:void 0,json:h,text:void 0}}}catch{return r()}}}Et(typeof FormData=="function","FormData is not available in this environment");let l,u;if(n.formData)l=h_(n.formData),u=n.formData;else if(n.body instanceof FormData)l=h_(n.body),u=n.body;else if(n.body instanceof URLSearchParams)l=n.body,u=BU(l);else if(n.body==null)l=new URLSearchParams,u=new FormData;else try{l=new URLSearchParams(n.body),u=BU(l)}catch{return r()}let f={formMethod:o,formAction:i,formEncType:n&&n.formEncType||"application/x-www-form-urlencoded",formData:u,json:void 0,text:void 0};if(Zr(f.formMethod))return{path:t,submission:f};let m=Ro(t);return e&&m.search&&rC(m.search)&&l.append("index",""),m.search=`?${l}`,{path:ga(m),submission:f}}function MU(e,t,n,r,a,o,i,l,u,f,m,h,g,b,E,x,w,S,_,T,k){let R=T?zr(T[1])?T[1].error:T[1].data:void 0,A=a.createURL(o.location),C=a.createURL(u),O;if(m&&o.errors){let te=Object.keys(o.errors)[0];O=i.findIndex(V=>V.route.id===te)}else if(T&&zr(T[1])){let te=T[0];O=i.findIndex(V=>V.route.id===te)-1}let M=T?T[1].statusCode:void 0,L=M&&M>=400,j={currentUrl:A,currentParams:o.matches[0]?.params||{},nextUrl:C,nextParams:i[0].params,...l,actionResult:R,actionStatus:M},B=Ys(i),K=i.map((te,V)=>{let{route:Y}=te,F=null;if(O!=null&&V>O?F=!1:Y.lazy?F=!0:tC(Y)?m?F=p_(Y,o.loaderData,o.errors):ife(o.loaderData,o.matches[V],te)&&(F=!0):F=!1,F!==null)return bm(n,r,e,B,te,f,t,F);let ae=!1;typeof k=="boolean"?ae=k:L?ae=!1:(h||A.pathname+A.search===C.pathname+C.search||A.search!==C.search||lfe(o.matches[V],te))&&(ae=!0);let ee={...j,defaultShouldRevalidate:ae},P=zp(te,ee);return bm(n,r,e,B,te,f,t,P,ee,k)}),Z=[];return E.forEach((te,V)=>{if(m||!i.some(D=>D.route.id===te.routeId)||b.has(V))return;let Y=o.fetchers.get(V),F=Y&&Y.state!=="idle"&&Y.data===void 0,ae=Uo(w,te.path,S);if(!ae){if(_&&F)return;Z.push({key:V,routeId:te.routeId,path:te.path,matches:null,match:null,request:null,controller:null});return}if(x.has(V))return;let ee=Ju(ae,te.path),P=new AbortController,H=Su(a,te.path,P.signal),U=null;if(g.has(V))g.delete(V),U=el(n,r,H,ae,ee,f,t);else if(F)h&&(U=el(n,r,H,ae,ee,f,t));else{let D;typeof k=="boolean"?D=k:L?D=!1:D=h;let $={...j,defaultShouldRevalidate:D};zp(ee,$)&&(U=el(n,r,H,ae,ee,f,t,$))}U&&Z.push({key:V,routeId:te.routeId,path:te.path,matches:U,match:ee,request:H,controller:P})}),{dsMatches:K,revalidatingFetchers:Z}}function tC(e){return e.loader!=null||e.middleware!=null&&e.middleware.length>0}function p_(e,t,n){if(e.lazy)return!0;if(!tC(e))return!1;let r=t!=null&&e.id in t,a=n!=null&&n[e.id]!==void 0;return!r&&a?!1:typeof e.loader=="function"&&e.loader.hydrate===!0?!0:!r&&!a}function ife(e,t,n){let r=!t||n.route.id!==t.route.id,a=!e.hasOwnProperty(n.route.id);return r||a}function lfe(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith("*")&&e.params["*"]!==t.params["*"]}function zp(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n=="boolean")return n}return t.defaultShouldRevalidate}function jU(e,t,n,r,a,o){let i;if(e){let f=r[e];Et(f,`No route found to patch children into: routeId = ${e}`),f.children||(f.children=[]),i=f.children}else i=n;let l=[],u=[];if(t.forEach(f=>{let m=i.find(h=>yV(f,h));m?u.push({existingRoute:m,newRoute:f}):l.push(f)}),l.length>0){let f=fc(l,a,[e||"_","patch",String(i?.length||"0")],r);i.push(...f)}if(o&&u.length>0)for(let f=0;f<u.length;f++){let{existingRoute:m,newRoute:h}=u[f],g=m,[b]=fc([h],a,[],{},!0);Object.assign(g,{element:b.element?b.element:g.element,errorElement:b.errorElement?b.errorElement:g.errorElement,hydrateFallbackElement:b.hydrateFallbackElement?b.hydrateFallbackElement:g.hydrateFallbackElement})}}function yV(e,t){return"id"in e&&"id"in t&&e.id===t.id?!0:e.index===t.index&&e.path===t.path&&e.caseSensitive===t.caseSensitive?(!e.children||e.children.length===0)&&(!t.children||t.children.length===0)?!0:e.children.every((n,r)=>t.children?.some(a=>yV(n,a))):!1}var PU=new WeakMap,nC=({key:e,route:t,manifest:n,mapRouteProperties:r})=>{let a=n[t.id];if(Et(a,"No route found in manifest"),!a.lazy||typeof a.lazy!="object")return;let o=a.lazy[e];if(!o)return;let i=PU.get(a);i||(i={},PU.set(a,i));let l=i[e];if(l)return l;let u=(async()=>{let f=Ade(e),h=a[e]!==void 0&&e!=="hasErrorBoundary";if(f)Un(!f,"Route property "+e+" is not a supported lazy route property. This property will be ignored."),i[e]=Promise.resolve();else if(h)Un(!1,`Route "${a.id}" has a static property "${e}" defined. The lazy property will be ignored.`);else{let g=await o();g!=null&&(Object.assign(a,{[e]:g}),Object.assign(a,r(a)))}typeof a.lazy=="object"&&(a.lazy[e]=void 0,Object.values(a.lazy).every(g=>g===void 0)&&(a.lazy=void 0))})();return i[e]=u,u},$U=new WeakMap;function cfe(e,t,n,r,a){let o=n[e.id];if(Et(o,"No route found in manifest"),!e.lazy)return{lazyRoutePromise:void 0,lazyHandlerPromise:void 0};if(typeof e.lazy=="function"){let m=$U.get(o);if(m)return{lazyRoutePromise:m,lazyHandlerPromise:m};let h=(async()=>{Et(typeof e.lazy=="function","No lazy route function found");let g=await e.lazy(),b={};for(let E in g){let x=g[E];if(x===void 0)continue;let w=Ode(E),_=o[E]!==void 0&&E!=="hasErrorBoundary";w?Un(!w,"Route property "+E+" is not a supported property to be returned from a lazy route function. This property will be ignored."):_?Un(!_,`Route "${o.id}" has a static property "${E}" defined but its lazy function is also returning a value for this property. The lazy route property "${E}" will be ignored.`):b[E]=x}Object.assign(o,b),Object.assign(o,{...r(o),lazy:void 0})})();return $U.set(o,h),h.catch(()=>{}),{lazyRoutePromise:h,lazyHandlerPromise:h}}let i=Object.keys(e.lazy),l=[],u;for(let m of i){if(a&&a.includes(m))continue;let h=nC({key:m,route:e,manifest:n,mapRouteProperties:r});h&&(l.push(h),m===t&&(u=h))}let f=l.length>0?Promise.all(l).then(()=>{}):void 0;return f?.catch(()=>{}),u?.catch(()=>{}),{lazyRoutePromise:f,lazyHandlerPromise:u}}function ufe(e){return e!==void 0}function UU(e,t,n){let r=e.map(({route:a})=>{if(!(typeof a.lazy!="object"||!a.lazy.middleware))return nC({key:"middleware",route:a,manifest:t,mapRouteProperties:n})}).filter(ufe);return r.length>0?Promise.all(r):void 0}async function m_(e){let t=e.matches.filter(a=>a.shouldLoad),n={};return(await Promise.all(t.map(a=>a.resolve()))).forEach((a,o)=>{n[t[o].route.id]=a}),n}async function dfe(e){return e.matches.some(t=>t.route.middleware)?vV(e,()=>m_(e)):m_(e)}function zU(e,t,n){return wV(e,t,r,ua,n);function r(a){return ac(a)?g_(a):a}}function vV(e,t){return wV(e,t,r=>{if(b_(r))throw r;return r},mfe,n);function n(r,a,o){if(o)return Promise.resolve(Object.assign(o.value,{[a]:{type:"error",result:r}}));{let{matches:i}=e,l=Math.min(Math.max(i.findIndex(f=>f.route.id===a),0),Math.max(i.findIndex(f=>f.shouldCallHandler()),0)),u=wo(i,i[l].route.id).route.id;return Promise.resolve({[u]:{type:"error",result:r}})}}}async function wV(e,t,n,r,a){let{matches:o,request:i,params:l,context:u,unstable_pattern:f}=e,m=o.flatMap(g=>g.route.middleware?g.route.middleware.map(b=>[g.route.id,b]):[]);return await xV({request:i,params:l,context:u,unstable_pattern:f},m,t,n,r,a)}async function xV(e,t,n,r,a,o,i=0){let{request:l}=e;if(l.signal.aborted)throw l.signal.reason??new Error(`Request aborted: ${l.method} ${l.url}`);let u=t[i];if(!u)return await n();let[f,m]=u,h,g=async()=>{if(h)throw new Error("You may only call `next()` once per middleware");try{return h={value:await xV(e,t,n,r,a,o,i+1)},h.value}catch(b){return h={value:await o(b,f,h)},h.value}};try{let b=await m(e,g),E=b!=null?r(b):void 0;return a(E)?E:h?E??h.value:(h={value:await g()},h.value)}catch(b){return await o(b,f,h)}}function EV(e,t,n,r,a){let o=nC({key:"middleware",route:r.route,manifest:t,mapRouteProperties:e}),i=cfe(r.route,Zr(n.method)?"action":"loader",t,e,a);return{middleware:o,route:i.lazyRoutePromise,handler:i.lazyHandlerPromise}}function bm(e,t,n,r,a,o,i,l,u=null,f){let m=!1,h=EV(e,t,n,a,o);return{...a,_lazyPromises:h,shouldLoad:l,shouldRevalidateArgs:u,shouldCallHandler(g){return m=!0,u?typeof f=="boolean"?zp(a,{...u,defaultShouldRevalidate:f}):typeof g=="boolean"?zp(a,{...u,defaultShouldRevalidate:g}):zp(a,u):l},resolve(g){let{lazy:b,loader:E,middleware:x}=a.route,w=m||l||g&&!Zr(n.method)&&(b||E),S=x&&x.length>0&&!E&&!b;return w&&(Zr(n.method)||!S)?ffe({request:n,unstable_pattern:r,match:a,lazyHandlerPromise:h?.handler,lazyRoutePromise:h?.route,handlerOverride:g,scopedContext:i}):Promise.resolve({type:"data",result:void 0})}}}function el(e,t,n,r,a,o,i,l=null){return r.map(u=>u.route.id!==a.route.id?{...u,shouldLoad:!1,shouldRevalidateArgs:l,shouldCallHandler:()=>!1,_lazyPromises:EV(e,t,n,u,o),resolve:()=>Promise.resolve({type:"data",result:void 0})}:bm(e,t,n,Ys(r),u,o,i,!0,l))}async function SV(e,t,n,r,a,o){n.some(f=>f._lazyPromises?.middleware)&&await Promise.all(n.map(f=>f._lazyPromises?.middleware));let i={request:t,unstable_pattern:Ys(n),params:n[0].params,context:a,matches:n},u=await e({...i,fetcherKey:r,runClientMiddleware:o?()=>{throw new Error("You cannot call `runClientMiddleware()` from a static handler `dataStrategy`. Middleware is run outside of `dataStrategy` during SSR in order to bubble up the Response. You can enable middleware via the `respond` API in `query`/`queryRoute`")}:f=>{let m=i;return vV(m,()=>f({...m,fetcherKey:r,runClientMiddleware:()=>{throw new Error("Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler")}}))}});try{await Promise.all(n.flatMap(f=>[f._lazyPromises?.handler,f._lazyPromises?.route]))}catch{}return u}async function ffe({request:e,unstable_pattern:t,match:n,lazyHandlerPromise:r,lazyRoutePromise:a,handlerOverride:o,scopedContext:i}){let l,u,f=Zr(e.method),m=f?"action":"loader",h=g=>{let b,E=new Promise((S,_)=>b=_);u=()=>b(),e.signal.addEventListener("abort",u);let x=S=>typeof g!="function"?Promise.reject(new Error(`You cannot call the handler for a route which defines a boolean "${m}" [routeId: ${n.route.id}]`)):g({request:e,unstable_pattern:t,params:n.params,context:i},...S!==void 0?[S]:[]),w=(async()=>{try{return{type:"data",result:await(o?o(_=>x(_)):x())}}catch(S){return{type:"error",result:S}}})();return Promise.race([w,E])};try{let g=f?n.route.action:n.route.loader;if(r||a)if(g){let b,[E]=await Promise.all([h(g).catch(x=>{b=x}),r,a]);if(b!==void 0)throw b;l=E}else{await r;let b=f?n.route.action:n.route.loader;if(b)[l]=await Promise.all([h(b),a]);else if(m==="action"){let E=new URL(e.url),x=E.pathname+E.search;throw Ar(405,{method:e.method,pathname:x,routeId:n.route.id})}else return{type:"data",result:void 0}}else if(g)l=await h(g);else{let b=new URL(e.url),E=b.pathname+b.search;throw Ar(404,{pathname:E})}}catch(g){return{type:"error",result:g}}finally{u&&e.signal.removeEventListener("abort",u)}return l}async function _V(e){let t=e.headers.get("Content-Type");return t&&/\bapplication\/json\b/.test(t)?e.body==null?null:e.json():e.text()}async function TV(e){let{result:t,type:n}=e;if(ua(t)){let r;try{r=await _V(t)}catch(a){return{type:"error",error:a}}return n==="error"?{type:"error",error:new ws(t.status,t.statusText,r),statusCode:t.status,headers:t.headers}:{type:"data",data:r,statusCode:t.status,headers:t.headers}}return n==="error"?ac(t)?t.data instanceof Error?{type:"error",error:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:"error",error:kV(t),statusCode:So(t)?t.status:void 0,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:"error",error:t,statusCode:So(t)?t.status:void 0}:ac(t)?{type:"data",data:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:"data",data:t}}function NV(e,t,n,r,a){let o=e.headers.get("Location");if(Et(o,"Redirects returned/thrown from loaders/actions must have a Location header"),!rw(o)){let i=r.slice(0,r.findIndex(l=>l.route.id===n)+1);o=f_(new URL(t.url),i,a,o),e.headers.set("Location",o)}return e}function FU(e,t,n,r){let a=["about:","blob:","chrome:","chrome-untrusted:","content:","data:","devtools:","file:","filesystem:","javascript:"];if(rw(e)){let o=e,i=o.startsWith("//")?new URL(t.protocol+o):new URL(o);if(a.includes(i.protocol))throw new Error("Invalid redirect location");let l=Na(i.pathname,n)!=null;if(i.origin===t.origin&&l)return i.pathname+i.search+i.hash}try{let o=r.createURL(e);if(a.includes(o.protocol))throw new Error("Invalid redirect location")}catch{}return e}function Su(e,t,n,r){let a=e.createURL(RV(t)).toString(),o={signal:n};if(r&&Zr(r.formMethod)){let{formMethod:i,formEncType:l}=r;o.method=i.toUpperCase(),l==="application/json"?(o.headers=new Headers({"Content-Type":l}),o.body=JSON.stringify(r.json)):l==="text/plain"?o.body=r.text:l==="application/x-www-form-urlencoded"&&r.formData?o.body=h_(r.formData):o.body=r.formData}return new Request(a,o)}function h_(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r=="string"?r:r.name);return t}function BU(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function CV(e,t,n,r=!1,a=!1){let o={},i=null,l,u=!1,f={},m=n&&zr(n[1])?n[1].error:void 0;return e.forEach(h=>{if(!(h.route.id in t))return;let g=h.route.id,b=t[g];if(Et(!Xi(b),"Cannot handle redirect results in processLoaderData"),zr(b)){let E=b.error;if(m!==void 0&&(E=m,m=void 0),i=i||{},a)i[g]=E;else{let x=wo(e,g);i[x.route.id]==null&&(i[x.route.id]=E)}r||(o[g]=bV),u||(u=!0,l=So(b.error)?b.error.status:500),b.headers&&(f[g]=b.headers)}else o[g]=b.data,b.statusCode&&b.statusCode!==200&&!u&&(l=b.statusCode),b.headers&&(f[g]=b.headers)}),m!==void 0&&n&&(i={[n[0]]:m},n[2]&&(o[n[2]]=void 0)),{loaderData:o,errors:i,statusCode:l||200,loaderHeaders:f}}function HU(e,t,n,r,a,o){let{loaderData:i,errors:l}=CV(t,n,r);return a.filter(u=>!u.matches||u.matches.some(f=>f.shouldLoad)).forEach(u=>{let{key:f,match:m,controller:h}=u;if(h&&h.signal.aborted)return;let g=o[f];if(Et(g,"Did not find corresponding fetcher result"),zr(g)){let b=wo(e.matches,m?.route.id);l&&l[b.route.id]||(l={...l,[b.route.id]:g.error}),e.fetchers.delete(f)}else if(Xi(g))Et(!1,"Unhandled fetcher revalidation redirect");else{let b=Gs(g.data);e.fetchers.set(f,b)}}),{loaderData:i,errors:l}}function VU(e,t,n,r){let a=Object.entries(t).filter(([,o])=>o!==bV).reduce((o,[i,l])=>(o[i]=l,o),{});for(let o of n){let i=o.route.id;if(!t.hasOwnProperty(i)&&e.hasOwnProperty(i)&&o.route.loader&&(a[i]=e[i]),r&&r.hasOwnProperty(i))break}return a}function GU(e){return e?zr(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function wo(e,t){return(t?e.slice(0,e.findIndex(r=>r.route.id===t)+1):[...e]).reverse().find(r=>r.route.hasErrorBoundary===!0)||e[0]}function ju(e){let t=e.length===1?e[0]:e.find(n=>n.index||!n.path||n.path==="/")||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function Ar(e,{pathname:t,routeId:n,method:r,type:a,message:o}={}){let i="Unknown Server Error",l="Unknown @remix-run/router error";return e===400?(i="Bad Request",r&&t&&n?l=`You made a ${r} request to "${t}" but did not provide a \`loader\` for route "${n}", so there is no way to handle the request.`:a==="invalid-body"&&(l="Unable to encode submission body")):e===403?(i="Forbidden",l=`Route "${n}" does not match URL "${t}"`):e===404?(i="Not Found",l=`No route matches URL "${t}"`):e===405&&(i="Method Not Allowed",r&&t&&n?l=`You made a ${r.toUpperCase()} request to "${t}" but did not provide an \`action\` for route "${n}", so there is no way to handle the request.`:r&&(l=`Invalid request method "${r.toUpperCase()}"`)),new ws(e||500,i,new Error(l),!0)}function Ab(e){let t=Object.entries(e);for(let n=t.length-1;n>=0;n--){let[r,a]=t[n];if(Xi(a))return{key:r,result:a}}}function RV(e){let t=typeof e=="string"?Ro(e):e;return ga({...t,hash:""})}function pfe(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===""?t.hash!=="":e.hash===t.hash?!0:t.hash!==""}function g_(e){return Response.json(e.data,e.init??void 0)}function kV(e){return new ws(e.init?.status??500,e.init?.statusText??"Internal Server Error",e.data)}function mfe(e){return e!=null&&typeof e=="object"&&Object.entries(e).every(([t,n])=>typeof t=="string"&&AV(n))}function AV(e){return e!=null&&typeof e=="object"&&"type"in e&&"result"in e&&(e.type==="data"||e.type==="error")}function IV(e){return ua(e.result)&&mV.has(e.result.status)}function zr(e){return e.type==="error"}function Xi(e){return(e&&e.type)==="redirect"}function ac(e){return typeof e=="object"&&e!=null&&"type"in e&&"data"in e&&"init"in e&&e.type==="DataWithResponseInit"}function ua(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.headers=="object"&&typeof e.body<"u"}function hfe(e){return mV.has(e)}function b_(e){return ua(e)&&hfe(e.status)&&e.headers.has("Location")}function y_(e){return nfe.has(e.toUpperCase())}function Zr(e){return efe.has(e.toUpperCase())}function rC(e){return new URLSearchParams(e).getAll("index").some(t=>t==="")}function Ju(e,t){let n=typeof t=="string"?Ro(t).search:t.search;if(e[e.length-1].route.index&&rC(n||""))return e[e.length-1];let r=sV(e);return r[r.length-1]}function WU(e){let{formMethod:t,formAction:n,formEncType:r,text:a,formData:o,json:i}=e;if(!(!t||!n||!r)){if(a!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:a};if(o!=null)return{formMethod:t,formAction:n,formEncType:r,formData:o,json:void 0,text:void 0};if(i!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:i,text:void 0}}}function UE(e,t){return t?{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}:{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function gfe(e,t){return{state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}function bp(e,t){return e?{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function bfe(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function Gs(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function yfe(e,t){try{let n=e.sessionStorage.getItem(gV);if(n){let r=JSON.parse(n);for(let[a,o]of Object.entries(r||{}))o&&Array.isArray(o)&&t.set(a,new Set(o||[]))}}catch{}}function vfe(e,t){if(t.size>0){let n={};for(let[r,a]of t)n[r]=[...a];try{e.sessionStorage.setItem(gV,JSON.stringify(n))}catch(r){Un(!1,`Failed to save applied view transitions in sessionStorage (${r}).`)}}}function KU(){let e,t,n=new Promise((r,a)=>{e=async o=>{r(o);try{await n}catch{}},t=async o=>{a(o);try{await n}catch{}}});return{promise:n,resolve:e,reject:t}}var si=y.createContext(null);si.displayName="DataRouter";var gl=y.createContext(null);gl.displayName="DataRouterState";var OV=y.createContext(!1);function DV(){return y.useContext(OV)}var sw=y.createContext({isTransitioning:!1});sw.displayName="ViewTransition";var iw=y.createContext(new Map);iw.displayName="Fetchers";var $d=y.createContext(null);$d.displayName="Await";var GTe=e=>y.createElement($d.Provider,e),ka=y.createContext(null);ka.displayName="Navigation";var lf=y.createContext(null);lf.displayName="Location";var oo=y.createContext({outlet:null,matches:[],isDataRoute:!1});oo.displayName="Route";var aC=y.createContext(null);aC.displayName="RouteError";var LV="REACT_ROUTER_ERROR",wfe="REDIRECT",xfe="ROUTE_ERROR_RESPONSE";function Efe(e){if(e.startsWith(`${LV}:${wfe}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.location=="string"&&typeof t.reloadDocument=="boolean"&&typeof t.replace=="boolean")return t}catch{}}function Sfe(e){if(e.startsWith(`${LV}:${xfe}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string")return new ws(t.status,t.statusText,t.data)}catch{}}function _fe(e,{relative:t}={}){Et(Tc(),"useHref() may be used only in the context of a <Router> component.");let{basename:n,navigator:r}=y.useContext(ka),{hash:a,pathname:o,search:i}=nh(e,{relative:t}),l=o;return n!=="/"&&(l=o==="/"?n:is([n,o])),r.createHref({pathname:l,search:i,hash:a})}function Tc(){return y.useContext(lf)!=null}function Aa(){return Et(Tc(),"useLocation() may be used only in the context of a <Router> component."),y.useContext(lf).location}function WTe(){return y.useContext(lf).navigationType}function KTe(e){Et(Tc(),"useMatch() may be used only in the context of a <Router> component.");let{pathname:t}=Aa();return y.useMemo(()=>gm(e,aV(t)),[t,e])}var MV="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function jV(e){y.useContext(ka).static||y.useLayoutEffect(e)}function bl(){let{isDataRoute:e}=y.useContext(oo);return e?$fe():Tfe()}function Tfe(){Et(Tc(),"useNavigate() may be used only in the context of a <Router> component.");let e=y.useContext(si),{basename:t,navigator:n}=y.useContext(ka),{matches:r}=y.useContext(oo),{pathname:a}=Aa(),o=JSON.stringify(aw(r)),i=y.useRef(!1);return jV(()=>{i.current=!0}),y.useCallback((u,f={})=>{if(Un(i.current,MV),!i.current)return;if(typeof u=="number"){n.go(u);return}let m=ow(u,JSON.parse(o),a,f.relative==="path");e==null&&t!=="/"&&(m.pathname=m.pathname==="/"?t:is([t,m.pathname])),(f.replace?n.replace:n.push)(m,f.state,f)},[t,n,o,a,e])}var PV=y.createContext(null);function YTe(){return y.useContext(PV)}function Nfe(e){let t=y.useContext(oo).outlet;return y.useMemo(()=>t&&y.createElement(PV.Provider,{value:e},t),[t,e])}function oC(){let{matches:e}=y.useContext(oo),t=e[e.length-1];return t?t.params:{}}function nh(e,{relative:t}={}){let{matches:n}=y.useContext(oo),{pathname:r}=Aa(),a=JSON.stringify(aw(n));return y.useMemo(()=>ow(e,JSON.parse(a),r,t==="path"),[e,a,r,t])}function Cfe(e,t){return sC(e,t)}function sC(e,t,n,r,a){Et(Tc(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:o}=y.useContext(ka),{matches:i}=y.useContext(oo),l=i[i.length-1],u=l?l.params:{},f=l?l.pathname:"/",m=l?l.pathnameBase:"/",h=l&&l.route;{let _=h&&h.path||"";zV(f,!h||_.endsWith("*")||_.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${f}" (under <Route path="${_}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
93
93
 
94
94
  Please change the parent <Route path="${_}"> to <Route path="${_==="/"?"*":`${_}/*`}">.`)}let g=Aa(),b;if(t){let _=typeof t=="string"?Ro(t):t;Et(m==="/"||_.pathname?.startsWith(m),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${m}" but pathname "${_.pathname}" was given in the \`location\` prop.`),b=_}else b=g;let E=b.pathname||"/",x=E;if(m!=="/"){let _=m.replace(/^\//,"").split("/");x="/"+E.replace(/^\//,"").split("/").slice(_.length).join("/")}let w=Uo(e,{pathname:x});Un(h||w!=null,`No routes matched location "${b.pathname}${b.search}${b.hash}" `),Un(w==null||w[w.length-1].route.element!==void 0||w[w.length-1].route.Component!==void 0||w[w.length-1].route.lazy!==void 0,`Matched leaf route at location "${b.pathname}${b.search}${b.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let S=UV(w&&w.map(_=>Object.assign({},_,{params:Object.assign({},u,_.params),pathname:is([m,o.encodeLocation?o.encodeLocation(_.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:_.pathname]),pathnameBase:_.pathnameBase==="/"?m:is([m,o.encodeLocation?o.encodeLocation(_.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:_.pathnameBase])})),i,n,r,a);return t&&S?y.createElement(lf.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",...b},navigationType:"POP"}},S):S}function Rfe(){let e=fC(),t=So(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r="rgba(200,200,200, 0.5)",a={padding:"0.5rem",backgroundColor:r},o={padding:"2px 4px",backgroundColor:r},i=null;return console.error("Error handled by React Router default ErrorBoundary:",e),i=y.createElement(y.Fragment,null,y.createElement("p",null,"💿 Hey developer 👋"),y.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",y.createElement("code",{style:o},"ErrorBoundary")," or"," ",y.createElement("code",{style:o},"errorElement")," prop on your route.")),y.createElement(y.Fragment,null,y.createElement("h2",null,"Unexpected Application Error!"),y.createElement("h3",{style:{fontStyle:"italic"}},t),n?y.createElement("pre",{style:a},n):null,i)}var kfe=y.createElement(Rfe,null),$V=class extends y.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error("React Router caught the following error during render",e)}render(){let e=this.state.error;if(this.context&&typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){const n=Sfe(e.digest);n&&(e=n)}let t=e!==void 0?y.createElement(oo.Provider,{value:this.props.routeContext},y.createElement(aC.Provider,{value:e,children:this.props.component})):this.props.children;return this.context?y.createElement(Afe,{error:e},t):t}};$V.contextType=OV;var zE=new WeakMap;function Afe({children:e,error:t}){let{basename:n}=y.useContext(ka);if(typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){let r=Efe(t.digest);if(r){let a=zE.get(t);if(a)throw a;let o=lV(r.location,n);if(iV&&!zE.get(t))if(o.isExternal||r.reloadDocument)window.location.href=o.absoluteURL||o.to;else{const i=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(o.to,{replace:r.replace}));throw zE.set(t,i),i}return y.createElement("meta",{httpEquiv:"refresh",content:`0;url=${o.absoluteURL||o.to}`})}}return e}function Ife({routeContext:e,match:t,children:n}){let r=y.useContext(si);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),y.createElement(oo.Provider,{value:e},n)}function UV(e,t=[],n=null,r=null,a=null){if(e==null){if(!n)return null;if(n.errors)e=n.matches;else if(t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let o=e,i=n?.errors;if(i!=null){let m=o.findIndex(h=>h.route.id&&i?.[h.route.id]!==void 0);Et(m>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(i).join(",")}`),o=o.slice(0,Math.min(o.length,m+1))}let l=!1,u=-1;if(n)for(let m=0;m<o.length;m++){let h=o[m];if((h.route.HydrateFallback||h.route.hydrateFallbackElement)&&(u=m),h.route.id){let{loaderData:g,errors:b}=n,E=h.route.loader&&!g.hasOwnProperty(h.route.id)&&(!b||b[h.route.id]===void 0);if(h.route.lazy||E){l=!0,u>=0?o=o.slice(0,u+1):o=[o[0]];break}}}let f=n&&r?(m,h)=>{r(m,{location:n.location,params:n.matches?.[0]?.params??{},unstable_pattern:Ys(n.matches),errorInfo:h})}:void 0;return o.reduceRight((m,h,g)=>{let b,E=!1,x=null,w=null;n&&(b=i&&h.route.id?i[h.route.id]:void 0,x=h.route.errorElement||kfe,l&&(u<0&&g===0?(zV("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),E=!0,w=null):u===g&&(E=!0,w=h.route.hydrateFallbackElement||null)));let S=t.concat(o.slice(0,g+1)),_=()=>{let T;return b?T=x:E?T=w:h.route.Component?T=y.createElement(h.route.Component,null):h.route.element?T=h.route.element:T=m,y.createElement(Ife,{match:h,routeContext:{outlet:m,matches:S,isDataRoute:n!=null},children:T})};return n&&(h.route.ErrorBoundary||h.route.errorElement||g===0)?y.createElement($V,{location:n.location,revalidation:n.revalidation,component:x,error:b,children:_(),routeContext:{outlet:null,matches:S,isDataRoute:!0},onError:f}):_()},null)}function iC(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function lC(e){let t=y.useContext(si);return Et(t,iC(e)),t}function ii(e){let t=y.useContext(gl);return Et(t,iC(e)),t}function Ofe(e){let t=y.useContext(oo);return Et(t,iC(e)),t}function cf(e){let t=Ofe(e),n=t.matches[t.matches.length-1];return Et(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function Dfe(){return cf("useRouteId")}function Lfe(){return ii("useNavigation").navigation}function ZTe(){let e=lC("useRevalidator"),t=ii("useRevalidator"),n=y.useCallback(async()=>{await e.router.revalidate()},[e.router]);return y.useMemo(()=>({revalidate:n,state:t.revalidation}),[n,t.revalidation])}function cC(){let{matches:e,loaderData:t}=ii("useMatches");return y.useMemo(()=>e.map(n=>eV(n,t)),[e,t])}function uC(){let e=ii("useLoaderData"),t=cf("useLoaderData");return e.loaderData[t]}function qTe(e){return ii("useRouteLoaderData").loaderData[e]}function dC(){let e=ii("useActionData"),t=cf("useLoaderData");return e.actionData?e.actionData[t]:void 0}function fC(){let e=y.useContext(aC),t=ii("useRouteError"),n=cf("useRouteError");return e!==void 0?e:t.errors?.[n]}function Mfe(){return y.useContext($d)?._data}function XTe(){return y.useContext($d)?._error}var jfe=0;function Pfe(e){let{router:t,basename:n}=lC("useBlocker"),r=ii("useBlocker"),[a,o]=y.useState(""),i=y.useCallback(l=>{if(typeof e!="function")return!!e;if(n==="/")return e(l);let{currentLocation:u,nextLocation:f,historyAction:m}=l;return e({currentLocation:{...u,pathname:Na(u.pathname,n)||u.pathname},nextLocation:{...f,pathname:Na(f.pathname,n)||f.pathname},historyAction:m})},[n,e]);return y.useEffect(()=>{let l=String(++jfe);return o(l),()=>t.deleteBlocker(l)},[t]),y.useEffect(()=>{a!==""&&t.getBlocker(a,i)},[t,a,i]),a&&r.blockers.has(a)?r.blockers.get(a):ql}function $fe(){let{router:e}=lC("useNavigate"),t=cf("useNavigate"),n=y.useRef(!1);return jV(()=>{n.current=!0}),y.useCallback(async(a,o={})=>{Un(n.current,MV),n.current&&(typeof a=="number"?await e.navigate(a):await e.navigate(a,{fromRouteId:t,...o}))},[e,t])}var YU={};function zV(e,t,n){!t&&!YU[e]&&(YU[e]=!0,Un(!1,n))}function JTe(...e){const t=cf("useRoute"),n=e[0]??t,r=ii("useRoute"),a=r.matches.find(({route:o})=>o.id===n);if(a!==void 0)return{handle:a.route.handle,loaderData:r.loaderData[n],actionData:r.actionData?.[n]}}var ZU={};function v_(e,t){!e&&!ZU[t]&&(ZU[t]=!0,console.warn(t))}var Ufe="useOptimistic",qU=Ec[Ufe],zfe=()=>{};function Ffe(e){return qU?qU(e):[e,zfe]}function rh(e){let t={hasErrorBoundary:e.hasErrorBoundary||e.ErrorBoundary!=null||e.errorElement!=null};return e.Component&&(e.element&&Un(!1,"You should not include both `Component` and `element` on your route - `Component` will be used."),Object.assign(t,{element:y.createElement(e.Component),Component:void 0})),e.HydrateFallback&&(e.hydrateFallbackElement&&Un(!1,"You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - `HydrateFallback` will be used."),Object.assign(t,{hydrateFallbackElement:y.createElement(e.HydrateFallback),HydrateFallback:void 0})),e.ErrorBoundary&&(e.errorElement&&Un(!1,"You should not include both `ErrorBoundary` and `errorElement` on your route - `ErrorBoundary` will be used."),Object.assign(t,{errorElement:y.createElement(e.ErrorBoundary),ErrorBoundary:void 0})),t}var pC=["HydrateFallback","hydrateFallbackElement"];function QTe(e,t){return eC({basename:t?.basename,getContext:t?.getContext,future:t?.future,history:ZH({initialEntries:t?.initialEntries,initialIndex:t?.initialIndex}),hydrationData:t?.hydrationData,routes:e,hydrationRouteProperties:pC,mapRouteProperties:rh,dataStrategy:t?.dataStrategy,patchRoutesOnNavigation:t?.patchRoutesOnNavigation,unstable_instrumentations:t?.unstable_instrumentations}).initialize()}var Bfe=class{constructor(){this.status="pending",this.promise=new Promise((e,t)=>{this.resolve=n=>{this.status==="pending"&&(this.status="resolved",e(n))},this.reject=n=>{this.status==="pending"&&(this.status="rejected",t(n))}})}};function eNe({router:e,flushSync:t,onError:n,unstable_useTransitions:r}){r=DV()||r;let[o,i]=y.useState(e.state),[l,u]=Ffe(o),[f,m]=y.useState(),[h,g]=y.useState({isTransitioning:!1}),[b,E]=y.useState(),[x,w]=y.useState(),[S,_]=y.useState(),T=y.useRef(new Map),k=y.useCallback((O,{deletedFetchers:M,newErrors:L,flushSync:j,viewTransitionOpts:B})=>{L&&n&&Object.values(L).forEach(Z=>n(Z,{location:O.location,params:O.matches[0]?.params??{},unstable_pattern:Ys(O.matches)})),O.fetchers.forEach((Z,te)=>{Z.data!==void 0&&T.current.set(te,Z.data)}),M.forEach(Z=>T.current.delete(Z)),v_(j===!1||t!=null,'You provided the `flushSync` option to a router update, but you are not using the `<RouterProvider>` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable. Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.');let K=e.window!=null&&e.window.document!=null&&typeof e.window.document.startViewTransition=="function";if(v_(B==null||K,"You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available."),!B||!K){t&&j?t(()=>i(O)):r===!1?i(O):y.startTransition(()=>{r===!0&&u(Z=>XU(Z,O)),i(O)});return}if(t&&j){t(()=>{x&&(b?.resolve(),x.skipTransition()),g({isTransitioning:!0,flushSync:!0,currentLocation:B.currentLocation,nextLocation:B.nextLocation})});let Z=e.window.document.startViewTransition(()=>{t(()=>i(O))});Z.finished.finally(()=>{t(()=>{E(void 0),w(void 0),m(void 0),g({isTransitioning:!1})})}),t(()=>w(Z));return}x?(b?.resolve(),x.skipTransition(),_({state:O,currentLocation:B.currentLocation,nextLocation:B.nextLocation})):(m(O),g({isTransitioning:!0,flushSync:!1,currentLocation:B.currentLocation,nextLocation:B.nextLocation}))},[e.window,t,x,b,r,u,n]);y.useLayoutEffect(()=>e.subscribe(k),[e,k]),y.useEffect(()=>{h.isTransitioning&&!h.flushSync&&E(new Bfe)},[h]),y.useEffect(()=>{if(b&&f&&e.window){let O=f,M=b.promise,L=e.window.document.startViewTransition(async()=>{r===!1?i(O):y.startTransition(()=>{r===!0&&u(j=>XU(j,O)),i(O)}),await M});L.finished.finally(()=>{E(void 0),w(void 0),m(void 0),g({isTransitioning:!1})}),w(L)}},[f,b,e.window,r,u]),y.useEffect(()=>{b&&f&&l.location.key===f.location.key&&b.resolve()},[b,x,l.location,f]),y.useEffect(()=>{!h.isTransitioning&&S&&(m(S.state),g({isTransitioning:!0,flushSync:!1,currentLocation:S.currentLocation,nextLocation:S.nextLocation}),_(void 0))},[h.isTransitioning,S]);let R=y.useMemo(()=>({createHref:e.createHref,encodeLocation:e.encodeLocation,go:O=>e.navigate(O),push:(O,M,L)=>e.navigate(O,{state:M,preventScrollReset:L?.preventScrollReset}),replace:(O,M,L)=>e.navigate(O,{replace:!0,state:M,preventScrollReset:L?.preventScrollReset})}),[e]),A=e.basename||"/",C=y.useMemo(()=>({router:e,navigator:R,static:!1,basename:A,onError:n}),[e,R,A,n]);return y.createElement(y.Fragment,null,y.createElement(si.Provider,{value:C},y.createElement(gl.Provider,{value:l},y.createElement(iw.Provider,{value:T.current},y.createElement(sw.Provider,{value:h},y.createElement(Nc,{basename:A,location:l.location,navigationType:l.historyAction,navigator:R,unstable_useTransitions:r},y.createElement(Hfe,{routes:e.routes,future:e.future,state:l,onError:n})))))),null)}function XU(e,t){return{...e,navigation:t.navigation.state!=="idle"?t.navigation:e.navigation,revalidation:t.revalidation!=="idle"?t.revalidation:e.revalidation,actionData:t.navigation.state!=="submitting"?t.actionData:e.actionData,fetchers:t.fetchers}}var Hfe=y.memo(Vfe);function Vfe({routes:e,future:t,state:n,onError:r}){return sC(e,void 0,n,r,t)}function tNe({basename:e,children:t,initialEntries:n,initialIndex:r,unstable_useTransitions:a}){let o=y.useRef();o.current==null&&(o.current=ZH({initialEntries:n,initialIndex:r,v5Compat:!0}));let i=o.current,[l,u]=y.useState({action:i.action,location:i.location}),f=y.useCallback(m=>{a===!1?u(m):y.startTransition(()=>u(m))},[a]);return y.useLayoutEffect(()=>i.listen(f),[i,f]),y.createElement(Nc,{basename:e,children:t,location:l.location,navigationType:l.action,navigator:i,unstable_useTransitions:a})}function nNe({to:e,replace:t,state:n,relative:r}){Et(Tc(),"<Navigate> may be used only in the context of a <Router> component.");let{static:a}=y.useContext(ka);Un(!a,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:o}=y.useContext(oo),{pathname:i}=Aa(),l=bl(),u=ow(e,aw(o),i,r==="path"),f=JSON.stringify(u);return y.useEffect(()=>{l(JSON.parse(f),{replace:t,state:n,relative:r})},[l,f,r,t,n]),null}function rNe(e){return Nfe(e.context)}function w_(e){Et(!1,"A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.")}function Nc({basename:e="/",children:t=null,location:n,navigationType:r="POP",navigator:a,static:o=!1,unstable_useTransitions:i}){Et(!Tc(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let l=e.replace(/^\/*/,"/"),u=y.useMemo(()=>({basename:l,navigator:a,static:o,unstable_useTransitions:i,future:{}}),[l,a,o,i]);typeof n=="string"&&(n=Ro(n));let{pathname:f="/",search:m="",hash:h="",state:g=null,key:b="default"}=n,E=y.useMemo(()=>{let x=Na(f,l);return x==null?null:{location:{pathname:x,search:m,hash:h,state:g,key:b},navigationType:r}},[l,f,m,h,g,b,r]);return Un(E!=null,`<Router basename="${l}"> is not able to match the URL "${f}${m}${h}" because it does not start with the basename, so the <Router> won't render anything.`),E==null?null:y.createElement(ka.Provider,{value:u},y.createElement(lf.Provider,{children:t,value:E}))}function Gfe({children:e,location:t}){return Cfe(Yy(e),t)}function aNe({children:e,errorElement:t,resolve:n}){let r=y.useContext(si),a=y.useContext(gl),o=y.useCallback((i,l)=>{r&&r.onError&&a&&r.onError(i,{location:a.location,params:a.matches[0]?.params||{},unstable_pattern:Ys(a.matches),errorInfo:l})},[r,a]);return y.createElement(Wfe,{resolve:n,errorElement:t,onError:o},y.createElement(Kfe,null,e))}var Wfe=class extends y.Component{constructor(e){super(e),this.state={error:null}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error("<Await> caught the following error during render",e,t)}render(){let{children:e,errorElement:t,resolve:n}=this.props,r=null,a=0;if(!(n instanceof Promise))a=1,r=Promise.resolve(),Object.defineProperty(r,"_tracked",{get:()=>!0}),Object.defineProperty(r,"_data",{get:()=>n});else if(this.state.error){a=2;let o=this.state.error;r=Promise.reject().catch(()=>{}),Object.defineProperty(r,"_tracked",{get:()=>!0}),Object.defineProperty(r,"_error",{get:()=>o})}else n._tracked?(r=n,a="_error"in r?2:"_data"in r?1:0):(a=0,Object.defineProperty(n,"_tracked",{get:()=>!0}),r=n.then(o=>Object.defineProperty(n,"_data",{get:()=>o}),o=>{this.props.onError?.(o),Object.defineProperty(n,"_error",{get:()=>o})}));if(a===2&&!t)throw r._error;if(a===2)return y.createElement($d.Provider,{value:r,children:t});if(a===1)return y.createElement($d.Provider,{value:r,children:e});throw r}};function Kfe({children:e}){let t=Mfe(),n=typeof e=="function"?e(t):e;return y.createElement(y.Fragment,null,n)}function Yy(e,t=[]){let n=[];return y.Children.forEach(e,(r,a)=>{if(!y.isValidElement(r))return;let o=[...t,a];if(r.type===y.Fragment){n.push.apply(n,Yy(r.props.children,o));return}Et(r.type===w_,`[${typeof r.type=="string"?r.type:r.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),Et(!r.props.index||!r.props.children,"An index route cannot have child routes.");let i={id:r.props.id||o.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,middleware:r.props.middleware,loader:r.props.loader,action:r.props.action,hydrateFallbackElement:r.props.hydrateFallbackElement,HydrateFallback:r.props.HydrateFallback,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.hasErrorBoundary===!0||r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(i.children=Yy(r.props.children,o)),n.push(i)}),n}var oNe=Yy;function sNe(e){return UV(e)}function FV(){return{params:oC(),loaderData:uC(),actionData:dC(),matches:cC()}}function iNe({children:e}){const t=FV();return y.cloneElement(e,t)}function lNe(e){return function(){const n=FV();return y.createElement(e,n)}}function BV(){return{params:oC(),loaderData:uC(),actionData:dC()}}function cNe({children:e}){const t=BV();return y.cloneElement(e,t)}function uNe(e){return function(){const n=BV();return y.createElement(e,n)}}function HV(){return{params:oC(),loaderData:uC(),actionData:dC(),error:fC()}}function dNe({children:e}){const t=HV();return y.cloneElement(e,t)}function fNe(e){return function(){const n=HV();return y.createElement(e,n)}}var sy="get",iy="application/x-www-form-urlencoded";function lw(e){return typeof HTMLElement<"u"&&e instanceof HTMLElement}function Yfe(e){return lw(e)&&e.tagName.toLowerCase()==="button"}function Zfe(e){return lw(e)&&e.tagName.toLowerCase()==="form"}function qfe(e){return lw(e)&&e.tagName.toLowerCase()==="input"}function Xfe(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Jfe(e,t){return e.button===0&&(!t||t==="_self")&&!Xfe(e)}function x_(e=""){return new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(a=>[n,a]):[[n,r]])},[]))}function Qfe(e,t){let n=x_(e);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(o=>{n.append(a,o)})}),n}var Ib=null;function epe(){if(Ib===null)try{new FormData(document.createElement("form"),0),Ib=!1}catch{Ib=!0}return Ib}var tpe=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function FE(e){return e!=null&&!tpe.has(e)?(Un(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${iy}"`),null):e}function npe(e,t){let n,r,a,o,i;if(Zfe(e)){let l=e.getAttribute("action");r=l?Na(l,t):null,n=e.getAttribute("method")||sy,a=FE(e.getAttribute("enctype"))||iy,o=new FormData(e)}else if(Yfe(e)||qfe(e)&&(e.type==="submit"||e.type==="image")){let l=e.form;if(l==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let u=e.getAttribute("formaction")||l.getAttribute("action");if(r=u?Na(u,t):null,n=e.getAttribute("formmethod")||l.getAttribute("method")||sy,a=FE(e.getAttribute("formenctype"))||FE(l.getAttribute("enctype"))||iy,o=new FormData(l,e),!epe()){let{name:f,type:m,value:h}=e;if(m==="image"){let g=f?`${f}.`:"";o.append(`${g}x`,"0"),o.append(`${g}y`,"0")}else f&&o.append(f,h)}}else{if(lw(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=sy,r=null,a=iy,i=e}return o&&a==="text/plain"&&(i=o,o=void 0),{action:r,method:n.toLowerCase(),encType:a,formData:o,body:i}}var VV=-1,GV=-2,WV=-3,KV=-4,mC=-5,YV=-6,ZV=-7,qV="B",XV="D",Qu="E",E_="M",JV="N",ed="P",QV="R",S_="S",e6="Y",t6="U",__="Z",n6=class{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}};function rpe(){const e=new TextDecoder;let t="";return new TransformStream({transform(n,r){const a=e.decode(n,{stream:!0}),o=(t+a).split(`
@@ -1750,7 +1750,7 @@ print(f"Available resources: {[resource.name for resource in resources]}")
1750
1750
  <\/script>
1751
1751
  </body>
1752
1752
  </html>`,nW=1,fF=2,rW=3,pF=4,aW=5,mF=Symbol.for("quilt.threads.serialize"),zSe=Symbol.for("quilt.threads.transferable");class FSe extends AbortController{constructor(...t){super();const n=t.find(r=>r.aborted);if(n)this.abort(n.reason);else{const r=o=>this.abort(o.target.reason),a={signal:this.signal};for(const o of t)o.addEventListener("abort",r,a)}}}class hF extends Error{constructor(){super("You attempted to call a function on a closed thread.")}}let BSe="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";function oW(e=21){let t="",n=crypto.getRandomValues(new Uint8Array(e));for(let r=0;r<e;r++)t+=BSe[63&n[r]];return t}var Op,Cu,Dp,wy,LT,sW;class HSe{constructor(){zo(this,LT),zo(this,Op,new Map),zo(this,Cu,new Map),zo(this,Dp,new Map),zo(this,wy,new WeakMap)}get(t){return sr(this,Cu).get(t)}release(t){const n=sr(this,Cu).get(t);return n&&(sr(this,Cu).delete(t),sr(this,Op).delete(n)),!!n}serialize(t){let n=sr(this,Op).get(t);return n==null&&(n=oW(),sr(this,Op).set(t,n),sr(this,Cu).set(n,t)),n}deserialize(t,n){var r,a;let o=(r=sr(this,Dp).get(t))==null?void 0:r.deref();return o||(o=(...i)=>{if(!sr(this,Dp).has(t))throw new Error("You attempted to call a function that was already revoked.");return n.call((l,u,f)=>{n.messages.send([rW,l,t,u],f)},i)},(a=qr(this,LT,sW).call(this,n))==null||a.register(o,t),sr(this,Dp).set(t,new WeakRef(o)),o)}}Op=new WeakMap,Cu=new WeakMap,Dp=new WeakMap,wy=new WeakMap,LT=new WeakSet,sW=function(e){let t=sr(this,wy).get(e);if(!(typeof FinalizationRegistry>"u"))return t||(t=new FinalizationRegistry(n=>{e.messages.send([aW,n])}),sr(this,wy).set(e,t)),t};function VSe(e){return e!=null&&(Symbol.asyncIterator in e||Symbol.iterator in e)&&typeof e.next=="function"}function gF(e){if(e==null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t==null||t===Object.prototype}const vS="_@f",bF="_@i";var Xp,Jp,bo,xy,Fi;class GSe{constructor(t){zo(this,bo),zo(this,Xp),zo(this,Jp),OT(this,Xp,t?.serialize),OT(this,Jp,t?.deserialize)}serialize(t,n,r){return qr(this,bo,xy).call(this,t,n,r)}deserialize(t,n){return qr(this,bo,Fi).call(this,t,n)}}Xp=new WeakMap,Jp=new WeakMap,bo=new WeakSet,xy=function(e,t,n,r=new Map,a=!1){if(e==null)return e;if(r.has(e))return r.get(e);if(r.set(e,void 0),typeof e=="object"){if(sr(this,Xp)&&!a){const l=sr(this,Xp).call(this,e,u=>qr(this,bo,xy).call(this,u,t,n,r,!0),t,n);if(l!==void 0)return r.set(e,l),l}if(e[zSe])return n?.push(e),r.set(e,e),e;const o=l=>qr(this,bo,xy).call(this,l,t,n,r);if(typeof e[mF]=="function"){const l=e[mF]({serialize:o});return r.set(e,l),l}if(Array.isArray(e)){const l=e.map(u=>o(u));return r.set(e,l),l}if(e instanceof Map){const l=[...e.entries()].map(([f,m])=>[o(f),o(m)]),u=new Map(l);return r.set(e,u),u}if(e instanceof Set){const l=[...e].map(f=>o(f)),u=new Set(l);return r.set(e,u),u}const i=VSe(e);if(gF(e)||i){const l={};for(const u of Object.keys(e))l[u]=o(e[u]);return i&&(l.next??(l.next=o(e.next.bind(e))),l.return??(l.return=o(e.return.bind(e))),l.throw??(l.throw=o(e.throw.bind(e))),l[bF]=!0),r.set(e,l),l}}if(typeof e=="function"){const o=t.functions.serialize(e,t,n),i={[vS]:o};return r.set(e,i),i}return r.set(e,e),e},Fi=function(e,t,n=!1){if(e==null)return e;if(typeof e=="object"){if(sr(this,Jp)&&!n){const a=sr(this,Jp).call(this,e,o=>qr(this,bo,Fi).call(this,o,t,!0),t);if(a!==void 0)return a}if(e==null)return e;if(Array.isArray(e))return e.map(a=>qr(this,bo,Fi).call(this,a,t));if(e instanceof Map)return new Map([...e].map(([a,o])=>[qr(this,bo,Fi).call(this,a,t),qr(this,bo,Fi).call(this,o,t)]));if(e instanceof Set)return new Set([...e].map(a=>qr(this,bo,Fi).call(this,a,t)));if(vS in e)return t.functions.deserialize(e[vS],t);if(!gF(e))return e;const r={};for(const a of Object.keys(e))a===bF?r[Symbol.asyncIterator]=()=>r:r[a]=qr(this,bo,Fi).call(this,e[a],t);return r}return e};var Ru,rc,Bi,MT,iW,jT,lW;class WSe{constructor(t,{imports:n,exports:r,functions:a=new HSe,serialization:o=new GSe,signal:i}={}){zo(this,Bi),zo(this,Ru),zo(this,rc,new Map);var l,u,f,m;this.messages=t,OT(this,Ru,i?new FSe(i):new AbortController),this.exports=r??{},this.imports=KSe(qr(this,Bi,iW).bind(this),n),this.functions=a,this.serialization=o,(u=(l=this.functions).start)==null||u.call(l,this),(m=(f=this.serialization).start)==null||m.call(f,this),this.signal.addEventListener("abort",()=>{for(const h of sr(this,rc).keys())qr(this,Bi,jT).call(this,h,void 0,new hF);sr(this,rc).clear()},{once:!0}),t.listen(async h=>{if(!(Array.isArray(h)&&typeof h[0]=="number"))return;const g=h;switch(g[0]){case nW:{const[,b,E,x]=g,w=this.exports[E]??(()=>{throw new Error(`No '${E}' method is exported from this thread`)});await qr(this,Bi,MT).call(this,w,x,(S,_,T)=>{this.messages.send([fF,b,S,_],T)});break}case rW:{const[,b,E,x]=g,w=this.functions.get(E,this)??YSe;await qr(this,Bi,MT).call(this,w,x,(S,_,T)=>{this.messages.send([pF,b,S,_],T)});break}case fF:case pF:{qr(this,Bi,jT).call(this,...g.slice(1));break}case aW:{const b=g[1];this.functions.release(b,this);break}}},{signal:this.signal})}get signal(){return sr(this,Ru).signal}get closed(){return sr(this,Ru).signal.aborted}close(){sr(this,Ru).abort()}call(t,n){if(this.closed)return Promise.reject(new hF);const r=[],a=this.serialization.serialize(n,this,r),o=oW(),i=qr(this,Bi,lW).call(this,o);return t(o,a,r),i}}Ru=new WeakMap,rc=new WeakMap,Bi=new WeakSet,MT=async function(e,t,n){try{const r=this.functions.call?await this.functions.call(e,t,this):await e(...this.serialization.deserialize(t,this)),a=[],o=this.serialization.serialize(r,this,a);n(o,void 0,a)}catch(r){n(void 0,this.serialization.serialize(r,this))}},iW=function(e){return(...t)=>{try{if(typeof e!="string"&&typeof e!="number")throw new Error(`Can’t call a symbol method on a thread: ${e.toString()}`);return this.call((n,r,a)=>{this.messages.send([nW,n,e,r],a)},t)}catch(n){return Promise.reject(n)}}},jT=function(...e){const t=e[0],n=sr(this,rc).get(t);n&&(n(...e),sr(this,rc).delete(t))},lW=function(e){const t=new Promise((n,r)=>{sr(this,rc).set(e,(a,o,i)=>{i==null?n(this.serialization.deserialize(o,this)):r(this.serialization.deserialize(i,this))})});return Object.defineProperty(t,Symbol.asyncIterator,{async*value(){const n=await t;Object.defineProperty(n,Symbol.asyncIterator,{value:()=>n}),yield*n}}),t};function KSe(e,t){let n;if(t==null){if(typeof Proxy!="function")throw new Error("You must pass an array of callable methods in environments without Proxies.");const r=new Map;n=new Proxy({},{get(a,o){if(r.has(o))return r.get(o);const i=e(o);return r.set(o,i),i}})}else{n={};for(const r of t)Object.defineProperty(n,r,{value:e(r),writable:!1,configurable:!0,enumerable:!0})}return n}function YSe(){throw new Error("You attempted to call a function that is not stored. It may have already been released.")}const ZSe="quilt.threads.ping",yF="quilt.threads.pong";function qSe(e,{targetOrigin:t="*"}={}){let n=!1;const r=function(o,i){e.postMessage(o,t,i)},a=new Promise(o=>{const i=new AbortController;globalThis.window.addEventListener("message",l=>{l.source===e&&l.data===yF&&(n=!0,i.abort(),o())},{signal:i.signal}),i.signal.addEventListener("abort",()=>o(),{once:!0}),r(ZSe)});return{send(o,i){return n?r(o,i):a.then(()=>{if(n)return r(o,i)})},listen(o,{signal:i}){self.addEventListener("message",l=>{l.source===e&&l.data!==yF&&o(l.data)},{signal:i})}}}class XSe extends WSe{constructor(t,{targetOrigin:n="*",...r}={}){super(qSe(t.contentWindow,{targetOrigin:n}),r),this.iframe=t}}const cW=le.forwardRef(({content:e,children:t,...n},r)=>d.jsx("span",{ref:r,...n,children:e||t}));cW.displayName="UIText";const uW=le.forwardRef(({label:e,onPress:t,onClick:n,children:r,...a},o)=>d.jsx("button",{ref:o,onClick:i=>{t&&t(),n&&n(i)},style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},...a,children:e||r}));uW.displayName="UIButton";const dW=le.forwardRef(({direction:e="vertical",spacing:t="8",align:n="stretch",justify:r="flex-start",children:a,...o},i)=>d.jsx("div",{ref:i,style:{display:"flex",flexDirection:e==="horizontal"?"row":"column",gap:`${t}px`,alignItems:n,justifyContent:r},...o,children:a}));dW.displayName="UIStack";const fW=le.forwardRef(({src:e,alt:t,width:n,height:r,children:a,...o},i)=>d.jsx("img",{ref:i,src:e,alt:t,width:n,height:r,style:{maxWidth:"100%",height:"auto",borderRadius:"8px",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.1)"},...o}));fW.displayName="UIImage";const BO={name:"basic",elements:[{tagName:"ui-text",component:cW,propMapping:{content:"content"},eventMapping:{}},{tagName:"ui-button",component:uW,propMapping:{label:"label"},eventMapping:{press:"onPress"}},{tagName:"ui-stack",component:dW,propMapping:{direction:"direction",spacing:"spacing",align:"align",justify:"justify"},eventMapping:{}},{tagName:"ui-image",component:fW,propMapping:{src:"src",alt:"alt",width:"width",height:"height"},eventMapping:{}}]},JSe=({receiver:e})=>{const t=y.useRef(null);return y.useEffect(()=>{if(t.current)return e.connect(t.current),()=>{e.disconnect()}},[e]),d.jsx("div",{ref:t,"data-testid":"standard-dom-renderer-container"})},QSe=({resource:e,library:t,remoteElements:n=[],onUIAction:r})=>{const a=y.useRef(null),o=y.useRef(null),[i,l]=y.useState(null),u=y.useMemo(()=>(e.mimeType||"").includes("framework=react")?"react":"webcomponents",[e.mimeType]),f=`${t?.name}-${u}`,{receiver:m,components:h}=y.useMemo(()=>{switch(u){case"react":{const b=new ASe,E=t||BO,x=new Map;return E&&E.elements.forEach(w=>{const S=jSe(w.component);x.set(w.tagName,S)}),{receiver:b,components:x}}case"webcomponents":default:return{receiver:new ISe,components:null}}},[e,t,n]);y.useEffect(()=>{function b(E){var x;if(a.current&&E.source===a.current.contentWindow){const w=E.data;if(!w)return;(x=r?.(w))==null||x.catch(S=>{console.error("Error handling UI action result in RemoteDOMResourceRenderer:",S)})}}return window.addEventListener("message",b),()=>window.removeEventListener("message",b)},[r]),y.useEffect(()=>{const b=o.current;return o.current=null,()=>{b?.close()}},[f]);const g=()=>{const b=a.current;if(!b||o.current)return;const E=new XSe(b);o.current=E;const{code:x,error:w}=xSe(e);if(w){l(w);return}if(x&&m!=null&&m.connection){const S={code:x,remoteElements:n,useReactRenderer:u==="react",componentLibrary:t?.name};E.imports.render(S,m.connection).catch(_=>console.error("Error calling remote render:",_))}};return i?d.jsx("p",{className:"text-red-500",children:i}):d.jsxs(d.Fragment,{children:[d.jsx("iframe",{ref:a,srcDoc:USe,sandbox:"allow-scripts",style:{display:"none"},title:"Remote DOM Sandbox",onLoad:g},f),u==="react"&&h?d.jsx($Se,{receiver:m,components:h}):d.jsx(JSe,{receiver:m})]})};function e_e(e){var t;if(e.contentType)return e.contentType;if(e.mimeType==="text/html")return"rawHtml";if(e.mimeType==="text/uri-list")return"externalUrl";if((t=e.mimeType)!=null&&t.startsWith("application/vnd.mcp-ui.remote-dom"))return"remoteDom"}const HO=e=>{const{resource:t,onUIAction:n,supportedContentTypes:r,htmlProps:a,remoteDomProps:o}=e,i=e_e(t);if(r&&i&&!r.includes(i))return d.jsxs("p",{className:"text-red-500",children:["Unsupported content type: ",i,"."]});switch(i){case"rawHtml":case"externalUrl":return d.jsx(q7,{resource:t,onUIAction:n,...a});case"remoteDom":return d.jsx(QSe,{resource:t,onUIAction:n,library:o?.library||BO,...o});default:return d.jsx("p",{className:"text-red-500",children:"Unsupported resource type."})}};HO.displayName="UIResourceRenderer";const t_e={tagName:"ui-button",remoteAttributes:["label"],remoteEvents:["click","press"]},n_e={tagName:"ui-text",remoteAttributes:["content"]},r_e={tagName:"ui-stack",remoteAttributes:["direction","spacing","align","justify"]},a_e={tagName:"ui-image",remoteAttributes:["src","alt","width","height"]},o_e=y.memo(({resource:e})=>{const t=async n=>(n.type==="tool"||n.type==="prompt"||(n.type==="link"?n.payload.url&&window.open(n.payload.url,"_blank"):n.type==="intent"||n.type),{status:"Action received"});return e.uri?.startsWith("ui://")?d.jsx("div",{className:"my-4 p-0 border h-[350px] rounded-2xl border-zinc-200 overflow-hidden bg-card",children:d.jsx(HO,{resource:e,onUIAction:t,htmlProps:{style:{maxWidth:"100%",height:"100%",overflow:"auto"},autoResizeIframe:!0,sandboxPermissions:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"}})}):null});function vF({toolName:e,toolArgs:t,result:n,serverId:r,readResource:a,toolMeta:o}){const[i,l]=y.useState(null);y.useEffect(()=>{console.log("[ToolResultRenderer] Rendering:",{toolName:e,hasToolMeta:!!o,outputTemplate:o?.["openai/outputTemplate"],hasResult:!!n,hasServerId:!!r,hasReadResource:!!a})},[e,o,n,r,a]);const u=y.useMemo(()=>{if(typeof n=="string")try{return JSON.parse(n)}catch(b){return console.error("[ToolResultRenderer] Failed to parse result:",b),n}return n},[n]),f=y.useMemo(()=>!!o?.["openai/outputTemplate"],[o]),m=y.useMemo(()=>!!(u?.content&&Array.isArray(u.content)&&u.content.some(b=>b.type==="resource"&&b.resource?.uri?.startsWith("ui://")&&b.resource?.mimeType==="text/html+skybridge")),[u]),h=y.useMemo(()=>m&&u.content.find(E=>E.type==="resource"&&E.resource?.uri?.startsWith("ui://")&&E.resource?.mimeType==="text/html+skybridge")?.resource||null,[m,u]);if(y.useEffect(()=>{if(h){l(h);return}if(f&&o&&a){const b=o["openai/outputTemplate"];console.log("[ToolResultRenderer] Fetching resource for Apps SDK tool:",b),a(b).then(E=>{console.log("[ToolResultRenderer] Resource fetched:",E),E?.contents&&Array.isArray(E.contents)&&E.contents.length>0?l(E.contents[0]):console.warn("[ToolResultRenderer] No contents in fetched resource:",E)}).catch(E=>{console.error("[ToolResultRenderer] Failed to fetch resource:",E)})}},[h,f,o,a]),(f||m)&&i&&r&&a)return d.jsx(PO,{componentUrl:i.uri,toolName:e,toolArgs:t,toolResult:u,serverId:r,readResource:a,noWrapper:!0,className:"my-4",showConsole:!1});if((f||m)&&!i)return d.jsx("div",{className:"flex items-center justify-center w-full h-[200px] rounded border",children:d.jsx(gs,{className:"size-5"})});if(f&&(!r||!a))return console.error("[ToolResultRenderer] Apps SDK tool but missing serverId or readResource:",{toolName:e,hasServerId:!!r,hasReadResource:!!a}),d.jsx("div",{className:"my-4 p-4 bg-red-50/30 dark:bg-red-950/20 border border-red-200/50 dark:border-red-800/50 rounded-lg",children:d.jsx("p",{className:"text-sm text-red-600 dark:text-red-400",children:"Cannot render widget: Missing required props (serverId or readResource)"})});const g=[];if(u?.content&&Array.isArray(u.content))for(const b of u.content)b.type==="resource"&&b.resource?.uri?.startsWith("ui://")&&b.resource?.mimeType!=="text/html+skybridge"&&g.push(b.resource);return g.length>0?d.jsx(d.Fragment,{children:g.map(b=>d.jsx(o_e,{resource:b},`${e}-mcp-ui-${b.uri}`))}):(console.log("[ToolResultRenderer] Not rendering (no UI resources found):",{toolName:e,isAppsSdkTool:f,hasAppsSdkComponent:m,hasResourceData:!!i,contentLength:u?.content?.length}),null)}function s_e({content:e,timestamp:t}){return!e||e.length===0?null:d.jsx("div",{className:"flex items-start gap-3 justify-end group/user-message",children:d.jsxs("div",{className:"flex-1 min-w-0 flex flex-col items-end",children:[d.jsx("div",{className:"bg-zinc-200 dark:bg-zinc-800 text-primary rounded-3xl px-4 py-2 max-w-[80%] break-words",children:d.jsx("p",{className:"text-base leading-7 font-sans text-start break-words",children:e})}),t&&d.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:new Date(t).toLocaleTimeString()})]})})}const i_e=y.memo(({messages:e,isLoading:t,serverId:n,readResource:r,tools:a})=>{const o=y.useRef(null),i=f=>a?.find(h=>h.name===f)?._meta;y.useEffect(()=>{e.length>0&&o.current&&o.current.scrollIntoView({behavior:t?"auto":"smooth",block:"start"})},[e.length,t]);const l=t&&(()=>{if(e.length===0)return!0;const f=e[e.length-1];if(f.role==="user")return!0;if(f.role==="assistant"){const m=typeof f.content=="string"?f.content:Array.isArray(f.content)?f.content.map(g=>typeof g=="string"?g:g.text||JSON.stringify(g)).join(""):JSON.stringify(f.content);return!(m&&m.trim().length>0)}return!1})(),u=f=>{if(!t)return!1;const m=e[e.length-1];return f.id===m.id&&m.role==="assistant"};return d.jsxs("div",{className:"space-y-6 max-w-3xl mx-auto px-2",children:[e.map(f=>{const m=typeof f.content=="string"?f.content:Array.isArray(f.content)?f.content.map(h=>typeof h=="string"?h:h.text||JSON.stringify(h)).join(""):JSON.stringify(f.content);return f.role==="user"?d.jsx(s_e,{content:m,timestamp:f.timestamp},f.id):f.role==="assistant"?d.jsx("div",{className:"space-y-4",children:f.parts&&f.parts.length>0?f.parts.map((h,g)=>{const b=h.type==="text"?`${f.id}-text-${g}-${h.text?.slice(0,20)}`:`${f.id}-tool-${h.toolInvocation?.toolName}-${g}`;return h.type==="text"?d.jsx(nF,{content:h.text||"",timestamp:g===f.parts.length-1?f.timestamp:void 0,_isStreaming:u(f)},b):h.type==="tool-invocation"&&h.toolInvocation?d.jsxs("div",{children:[d.jsx(rF,{toolName:h.toolInvocation.toolName,args:h.toolInvocation.args,result:h.toolInvocation.result,state:h.toolInvocation.result?"result":"call"}),h.toolInvocation.result&&d.jsx(vF,{toolName:h.toolInvocation.toolName,toolArgs:h.toolInvocation.args,result:h.toolInvocation.result,serverId:n,readResource:r,toolMeta:i(h.toolInvocation.toolName)})]},b):null}):d.jsxs(d.Fragment,{children:[d.jsx(nF,{content:m,timestamp:f.timestamp,_isStreaming:u(f)}),f.toolCalls&&f.toolCalls.length>0&&d.jsx("div",{className:"space-y-2",children:f.toolCalls.map(h=>{const g=`${f.id}-${h.toolName}-${JSON.stringify(h.args).slice(0,50)}`;return d.jsxs("div",{children:[d.jsx(rF,{toolName:h.toolName,args:h.args,result:h.result,state:h.result?"result":"call"}),h.result&&d.jsx(vF,{toolName:h.toolName,toolArgs:h.args,result:h.result,serverId:n,readResource:r,toolMeta:i(h.toolName)})]},g)})})]})},f.id):null}),l&&d.jsx("div",{className:"flex items-start gap-3",children:d.jsx("div",{className:"flex-1",children:d.jsx("div",{className:"rounded-lg p-4 max-w-fit",children:d.jsx("div",{className:"flex items-center gap-2",children:d.jsx("span",{className:"text-sm",children:d.jsx(zxe,{duration:2,spread:1,children:"Thinking..."})})})})})}),d.jsx("div",{ref:o})]})});function pW(e){let t=0;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);t=(t<<5)-t+r,t=t&t}return Math.abs(t).toString(16)}function l_e({mcpServerUrl:e,llmConfig:t,authConfig:n,isConnected:r}){const[a,o]=y.useState([]),[i,l]=y.useState(!1),u=y.useCallback(async m=>{if(!m.trim()||!t||!r)return;const h={id:`user-${Date.now()}`,role:"user",content:m.trim(),timestamp:Date.now()};o(g=>[...g,h]),l(!0);try{let g=n;if(n?.type==="oauth")try{const k="mcp:auth",R=pW(e),A=`${k}_${R}_tokens`,C=localStorage.getItem(A);if(C){const O=JSON.parse(C);g={...n,oauthTokens:O}}else console.warn("No OAuth tokens found in localStorage for key:",A)}catch(k){console.warn("Failed to retrieve OAuth tokens:",k)}const b=await fetch("/inspector/api/chat/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mcpServerUrl:e,llmConfig:t,authConfig:g,messages:[...a,h].map(k=>({role:k.role,content:k.content}))})});if(!b.ok)throw new Error(`HTTP error! status: ${b.status}`);const E=`assistant-${Date.now()}`;let x="";const w=[];o(k=>[...k,{id:E,role:"assistant",content:"",timestamp:Date.now(),parts:[]}]);const S=b.body?.getReader(),_=new TextDecoder;if(!S)throw new Error("No response body");let T="";for(;;){const{done:k,value:R}=await S.read();if(k)break;T+=_.decode(R,{stream:!0});const A=T.split(`
1753
- `);T=A.pop()||"";for(const C of A)if(C.trim()&&C.startsWith("data: "))try{const O=JSON.parse(C.slice(6));if(console.log("[Client received event]",O.type,O.toolName||O.content?.slice?.(0,30)),O.type==="message")console.log("[Message started]",O.id);else if(O.type==="text"){x+=O.content;const M=w[w.length-1];M&&M.type==="text"?M.text=x:w.push({type:"text",text:x}),console.log("[Parts after text]",w.length,"parts, text length:",x.length),o(L=>L.map(j=>j.id===E?{...j,parts:[...w]}:j))}else if(O.type==="tool-call")x&&(x=""),w.push({type:"tool-invocation",toolInvocation:{toolName:O.toolName,args:O.args,state:"pending"}}),console.log("[Parts after tool-call]",w.length,"parts, tool:",O.toolName),o(M=>M.map(L=>L.id===E?{...L,parts:[...w]}:L));else if(O.type==="tool-result"){const M=w.find(L=>L.type==="tool-invocation"&&L.toolInvocation?.toolName===O.toolName&&!L.toolInvocation?.result);M&&M.toolInvocation?(M.toolInvocation.result=O.result,M.toolInvocation.state="result",console.log("[Parts after tool-result]",w.length,"parts, updated:",O.toolName),o(L=>L.map(j=>j.id===E?{...j,parts:[...w]}:j))):console.warn("[tool-result] Could not find matching tool part for",O.toolName)}else if(O.type==="done")console.log("[Done] Final parts:",w.length),o(M=>M.map(L=>L.id===E?{...L,parts:[...w],content:""}:L));else if(O.type==="error")throw new Error(O.message||"Streaming error")}catch(O){console.error("Failed to parse streaming event:",O,C)}}}catch(g){let b="Unknown error occurred";if(g instanceof Error){b=g.message;const x=g;x.status&&(b=`HTTP ${x.status}: ${b}`),(x.code===401||b.includes("401")||b.includes("Unauthorized"))&&(b="Authentication failed (401). Check your Authorization header in the connection settings.")}const E={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${b}`,timestamp:Date.now()};o(x=>[...x,E])}finally{l(!1)}},[t,r,e,a,n]),f=y.useCallback(()=>{o([])},[]);return{messages:a,isLoading:i,sendMessage:u,clearMessages:f}}function c_e({connection:e,llmConfig:t,isConnected:n,readResource:r}){const[a,o]=y.useState([]),[i,l]=y.useState(!1),u=y.useRef(null),f=y.useRef(null),m=y.useRef(null),h=y.useCallback(async b=>{if(!b.trim()||!t||!n)return;const E={id:`user-${Date.now()}`,role:"user",content:b.trim(),timestamp:Date.now()};o(S=>[...S,E]),l(!0),u.current=new AbortController;const x=Date.now();let w=0;try{const S=`assistant-${Date.now()}`;let _="";const T=[];if(o(k=>[...k,{id:S,role:"assistant",content:"",timestamp:Date.now(),parts:[]}]),!m.current||m.current.provider!==t.provider||m.current.model!==t.model||m.current.apiKey!==t.apiKey){let k;if(t.provider==="openai"){const{ChatOpenAI:R}=await Ua(async()=>{const{ChatOpenAI:A}=await import("./index-DnfVI-Ze.js");return{ChatOpenAI:A}},__vite__mapDeps([0,1,2,3,4,5]));k=new R({model:t.model,apiKey:t.apiKey})}else if(t.provider==="anthropic"){const{ChatAnthropic:R}=await Ua(async()=>{const{ChatAnthropic:A}=await import("./index-BmT6F6tU.js");return{ChatAnthropic:A}},__vite__mapDeps([6,2,1,5]));k=new R({model:t.model,apiKey:t.apiKey})}else if(t.provider==="google"){const{ChatGoogleGenerativeAI:R}=await Ua(async()=>{const{ChatGoogleGenerativeAI:A}=await import("./index-DqIRqeuh.js");return{ChatGoogleGenerativeAI:A}},__vite__mapDeps([7,2,1,4]));k=new R({model:t.model,apiKey:t.apiKey})}else throw new Error(`Unsupported LLM provider: ${t.provider}`);m.current={instance:k,provider:t.provider,model:t.model,apiKey:t.apiKey}}if(!f.current||f.current.llm!==m.current.instance){const{MCPAgent:k}=await Ua(async()=>{const{MCPAgent:R}=await import("./browser-CB208uLg.js");return{MCPAgent:R}},__vite__mapDeps([8,5,1,2,4,3]));f.current=new k({llm:m.current.instance,client:e.client,memoryEnabled:!0,systemPrompt:"You are a helpful assistant with access to MCP tools, prompts, and resources. Help users interact with the MCP server."}),await f.current.initialize()}else console.log("[useChatMessagesClientSide] Reusing existing agent. History length:",f.current.conversationHistory?.length);for await(const k of f.current.streamEvents(b,10,!1,void 0)){if(u.current?.signal.aborted)break;if(k.event==="on_chat_model_stream"&&k.data?.chunk?.text){const R=k.data.chunk.text;if(typeof R=="string"&&R.length>0){_+=R;const A=T[T.length-1];A&&A.type==="text"?A.text=_:T.push({type:"text",text:_}),o(C=>C.map(O=>O.id===S?{...O,parts:[...T]}:O))}}else if(k.event==="on_tool_start"){_&&(_="");let R={};k.data?.input?R=k.data.input:k.data?.tool_input?R=k.data.tool_input:k.data&&(R=k.data),console.log("[useChatMessagesClientSide] on_tool_start:",{toolName:k.name,eventData:k.data,extractedArgs:R}),w++,T.push({type:"tool-invocation",toolInvocation:{toolName:k.name||"unknown",args:R,state:"pending"}}),o(A=>A.map(C=>C.id===S?{...C,parts:[...T]}:C))}else if(k.event==="on_tool_end"){const R=T.find(A=>A.type==="tool-invocation"&&A.toolInvocation?.toolName===k.name&&!A.toolInvocation?.result);if(console.log("[useChatMessagesClientSide] on_tool_end event:",{toolName:k.name,hasToolPart:!!R,output:k.data?.output}),R&&R.toolInvocation){let A=k.data?.output;if(A?.kwargs?.content&&typeof A.kwargs.content=="string")try{A=JSON.parse(A.kwargs.content)}catch(O){console.warn("[useChatMessagesClientSide] Failed to parse kwargs.content:",O),A=A.kwargs.content}else if(A?.content&&typeof A.content=="string")try{A=JSON.parse(A.content)}catch{A=A.content}R.toolInvocation.result=A,R.toolInvocation.state="result";const C=A?._meta?.["openai/outputTemplate"];if(console.log("[useChatMessagesClientSide] Tool result:",{toolName:k.name,hasMeta:!!A?._meta,hasStructuredContent:!!A?.structuredContent,appsSdkUri:C}),C&&typeof C=="string"&&r){console.log("[useChatMessagesClientSide] Detected Apps SDK component, fetching resource:",C);try{const O=await r(C);console.log("[useChatMessagesClientSide] Resource fetched:",O);const M=A?.structuredContent||null;if(O?.contents&&Array.isArray(O.contents)){const L=O.contents.map(B=>({type:"resource",resource:B}));console.log("[useChatMessagesClientSide] Created MCP resources:",L);const j={...A,content:[...A.content||[],...L],structuredContent:M};R.toolInvocation.result=j,console.log("[useChatMessagesClientSide] Updated result with resources")}else console.warn("[useChatMessagesClientSide] No contents in resourceData:",O)}catch(O){console.error("Failed to fetch Apps SDK resource:",O)}}o(O=>O.map(M=>M.id===S?{...M,parts:[...T]}:M))}}}o(k=>k.map(R=>R.id===S?{...R,parts:[...T],content:""}:R)),t&&ra.getInstance().capture(new yU({serverId:e.url,provider:t.provider,model:t.model,messageCount:a.length+1,toolCallsCount:w,success:!0,executionMode:"client-side",duration:Date.now()-x})).catch(()=>{})}catch(S){console.error("Client-side agent error:",S);let _="Unknown error occurred";if(S instanceof Error){_=S.message;const k=S;k.status&&(_=`HTTP ${k.status}: ${_}`),(k.code===401||_.includes("401")||_.includes("Unauthorized"))&&(_="Authentication failed (401). Check your Authorization header in the connection settings.")}t&&ra.getInstance().capture(new yU({serverId:e.url,provider:t.provider,model:t.model,messageCount:a.length+1,toolCallsCount:w,success:!1,executionMode:"client-side",duration:Date.now()-x,error:_})).catch(()=>{});const T={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${_}`,timestamp:Date.now()};o(k=>[...k,T])}finally{l(!1),u.current=null}},[e,t,n,a,r]),g=y.useCallback(()=>{o([]),f.current&&f.current.clearConversationHistory()},[]);return{messages:a,isLoading:i,sendMessage:h,clearMessages:g}}const wF={openai:"gpt-4o",anthropic:"claude-haiku-4-5-20251001",google:"gemini-2.5-flash"};function mW({mcpServerUrl:e}){const[t,n]=y.useState(null),[r,a]=y.useState(null),[o,i]=y.useState(!1),[l,u]=y.useState("openai"),[f,m]=y.useState(""),[h,g]=y.useState(wF.openai),b=y.useCallback(()=>{const M=localStorage.getItem("mcp-inspector-api-keys");if(M)try{return JSON.parse(M)}catch(L){return console.error("Failed to load API keys:",L),{}}return{}},[]),E=y.useCallback(M=>{localStorage.setItem("mcp-inspector-api-keys",JSON.stringify(M))},[]),[x,w]=y.useState("none"),[S,_]=y.useState(""),[T,k]=y.useState(""),[R,A]=y.useState("");y.useEffect(()=>{const M=localStorage.getItem("mcp-inspector-llm-config"),L=b();if(M)try{const j=JSON.parse(M);n(j),u(j.provider),m(L[j.provider]||j.apiKey||""),g(j.model)}catch(j){console.error("Failed to load LLM config:",j)}},[b]),y.useEffect(()=>{const M=localStorage.getItem("mcp-inspector-auth-config");if(M)try{const L=JSON.parse(M);a(L),w(L.type),L.username&&_(L.username),L.password&&k(L.password),L.token&&A(L.token)}catch(L){console.error("Failed to load auth config:",L)}else try{const L="mcp:auth",j=pW(e),B=`${L}_${j}_tokens`;localStorage.getItem(B)&&(a({type:"oauth"}),w("oauth"))}catch(L){console.error("Failed to check for OAuth tokens:",L)}},[e]),y.useEffect(()=>{g(wF[l]);const M=b();m(M[l]||"")},[l,b]);const C=y.useCallback(()=>{if(!f.trim())return;const M=b();M[l]=f,E(M);const L={provider:l,apiKey:f,model:h},j={type:x,...x==="basic"&&{username:S.trim(),password:T.trim()},...x==="bearer"&&{token:R.trim()}};n(L),a(j),localStorage.setItem("mcp-inspector-llm-config",JSON.stringify(L)),localStorage.setItem("mcp-inspector-auth-config",JSON.stringify(j)),i(!1)},[l,f,h,x,S,T,R,b,E]),O=y.useCallback(()=>{n(null),a(null);const M=b();delete M[l],E(M),m(""),_(""),k(""),A(""),w("none"),localStorage.removeItem("mcp-inspector-llm-config"),localStorage.removeItem("mcp-inspector-auth-config")},[l,b,E]);return{llmConfig:t,authConfig:r,configDialogOpen:o,setConfigDialogOpen:i,tempProvider:l,setTempProvider:u,tempApiKey:f,setTempApiKey:m,tempModel:h,setTempModel:g,tempAuthType:x,saveLLMConfig:C,clearConfig:O}}function u_e({connection:e,isConnected:t,useClientSide:n=!0,readResource:r}){const[a,o]=y.useState(""),i=y.useRef(null),{llmConfig:l,authConfig:u,configDialogOpen:f,setConfigDialogOpen:m,tempProvider:h,setTempProvider:g,tempApiKey:b,setTempApiKey:E,tempModel:x,setTempModel:w,saveLLMConfig:S,clearConfig:_}=mW({mcpServerUrl:e.url}),T={connection:e,llmConfig:l,isConnected:t,readResource:r},k=l_e({mcpServerUrl:e.url,llmConfig:l,authConfig:u,isConnected:t}),R=c_e(T),{messages:A,isLoading:C,sendMessage:O,clearMessages:M}=n?R:k;NG({onNewChat:M}),y.useEffect(()=>{l&&A.length===0&&i.current&&i.current.focus()},[l,A.length]),y.useEffect(()=>{!C&&A.length>0&&i.current&&i.current.focus()},[C,A.length]);const L=y.useCallback(()=>{a.trim()&&(O(a),o(""))},[a,O]),j=y.useCallback(K=>{K.key==="Enter"&&!K.shiftKey&&(K.preventDefault(),L())},[L]),B=y.useCallback(()=>{_(),M()},[_,M]);return l&&A.length===0?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsx("div",{className:"absolute top-4 right-4 z-10",children:d.jsx(gT,{open:f,onOpenChange:m,tempProvider:h,tempModel:x,tempApiKey:b,onProviderChange:g,onModelChange:w,onApiKeyChange:E,onSave:S,onClear:B,showClearButton:!0,buttonLabel:"Change API Key"})}),d.jsx($xe,{mcpServerUrl:e.url,inputValue:a,isConnected:t,isLoading:C,textareaRef:i,llmConfig:l,onInputChange:o,onKeyDown:j,onSubmit:K=>{K.preventDefault(),L()},onConfigDialogOpenChange:m})]}):d.jsxs("div",{className:"flex flex-col h-full relative",children:[d.jsx(Mxe,{llmConfig:l,hasMessages:A.length>0,configDialogOpen:f,onConfigDialogOpenChange:m,onClearChat:M,tempProvider:h,tempModel:x,tempApiKey:b,onProviderChange:g,onModelChange:w,onApiKeyChange:E,onSaveConfig:S,onClearConfig:B}),d.jsx("div",{className:"flex-1 overflow-y-auto p-2 sm:p-4 pt-[80px] sm:pt-[100px]",children:l?d.jsx(i_e,{messages:A,isLoading:C,serverId:e.url,readResource:r,tools:e.tools}):d.jsx(Uxe,{onConfigureClick:()=>m(!0)})}),l&&d.jsx(jxe,{inputValue:a,isConnected:t,isLoading:C,textareaRef:i,onInputChange:o,onKeyDown:j,onSendMessage:L})]})}const Uw=y.createContext(null);Uw.displayName="PanelGroupContext";const br={group:"data-panel-group",groupDirection:"data-panel-group-direction",groupId:"data-panel-group-id",panel:"data-panel",panelCollapsible:"data-panel-collapsible",panelId:"data-panel-id",panelSize:"data-panel-size",resizeHandle:"data-resize-handle",resizeHandleActive:"data-resize-handle-active",resizeHandleEnabled:"data-panel-resize-handle-enabled",resizeHandleId:"data-panel-resize-handle-id",resizeHandleState:"data-resize-handle-state"},VO=10,ic=y.useLayoutEffect,xF=Ec.useId,d_e=typeof xF=="function"?xF:()=>null;let f_e=0;function GO(e=null){const t=d_e(),n=y.useRef(e||t||null);return n.current===null&&(n.current=""+f_e++),e??n.current}function hW({children:e,className:t="",collapsedSize:n,collapsible:r,defaultSize:a,forwardedRef:o,id:i,maxSize:l,minSize:u,onCollapse:f,onExpand:m,onResize:h,order:g,style:b,tagName:E="div",...x}){const w=y.useContext(Uw);if(w===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:S,expandPanel:_,getPanelSize:T,getPanelStyle:k,groupId:R,isPanelCollapsed:A,reevaluatePanelConstraints:C,registerPanel:O,resizePanel:M,unregisterPanel:L}=w,j=GO(i),B=y.useRef({callbacks:{onCollapse:f,onExpand:m,onResize:h},constraints:{collapsedSize:n,collapsible:r,defaultSize:a,maxSize:l,minSize:u},id:j,idIsFromProps:i!==void 0,order:g});y.useRef({didLogMissingDefaultSizeWarning:!1}),ic(()=>{const{callbacks:Z,constraints:te}=B.current,V={...te};B.current.id=j,B.current.idIsFromProps=i!==void 0,B.current.order=g,Z.onCollapse=f,Z.onExpand=m,Z.onResize=h,te.collapsedSize=n,te.collapsible=r,te.defaultSize=a,te.maxSize=l,te.minSize=u,(V.collapsedSize!==te.collapsedSize||V.collapsible!==te.collapsible||V.maxSize!==te.maxSize||V.minSize!==te.minSize)&&C(B.current,V)}),ic(()=>{const Z=B.current;return O(Z),()=>{L(Z)}},[g,j,O,L]),y.useImperativeHandle(o,()=>({collapse:()=>{S(B.current)},expand:Z=>{_(B.current,Z)},getId(){return j},getSize(){return T(B.current)},isCollapsed(){return A(B.current)},isExpanded(){return!A(B.current)},resize:Z=>{M(B.current,Z)}}),[S,_,T,A,j,M]);const K=k(B.current,a);return y.createElement(E,{...x,children:e,className:t,id:j,style:{...K,...b},[br.groupId]:R,[br.panel]:"",[br.panelCollapsible]:r||void 0,[br.panelId]:j,[br.panelSize]:parseFloat(""+K.flexGrow).toFixed(1)})}const gW=y.forwardRef((e,t)=>y.createElement(hW,{...e,forwardedRef:t}));hW.displayName="Panel";gW.displayName="forwardRef(Panel)";let PT=null,Ey=-1,Ki=null;function p_e(e,t,n){const r=(t&xW)!==0,a=(t&EW)!==0,o=(t&SW)!==0,i=(t&_W)!==0;if(t){if(r)return o?"se-resize":i?"ne-resize":"e-resize";if(a)return o?"sw-resize":i?"nw-resize":"w-resize";if(o)return"s-resize";if(i)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function m_e(){Ki!==null&&(document.head.removeChild(Ki),PT=null,Ki=null,Ey=-1)}function wS(e,t,n){var r,a;const o=p_e(e,t);if(PT!==o){if(PT=o,Ki===null&&(Ki=document.createElement("style"),document.head.appendChild(Ki)),Ey>=0){var i;(i=Ki.sheet)===null||i===void 0||i.removeRule(Ey)}Ey=(r=(a=Ki.sheet)===null||a===void 0?void 0:a.insertRule(`*{cursor: ${o} !important;}`))!==null&&r!==void 0?r:-1}}function bW(e){return e.type==="keydown"}function yW(e){return e.type.startsWith("pointer")}function vW(e){return e.type.startsWith("mouse")}function zw(e){if(yW(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(vW(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function h_e(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function g_e(e,t,n){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function b_e(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:_F(e),b:_F(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),r=e;tn(r,"Stacking order can only be calculated for elements with a common ancestor");const a={a:SF(EF(n.a)),b:SF(EF(n.b))};if(a.a===a.b){const o=r.childNodes,i={a:n.a.at(-1),b:n.b.at(-1)};let l=o.length;for(;l--;){const u=o[l];if(u===i.a)return 1;if(u===i.b)return-1}}return Math.sign(a.a-a.b)}const y_e=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function v_e(e){var t;const n=getComputedStyle((t=wW(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function w_e(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||v_e(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||y_e.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function EF(e){let t=e.length;for(;t--;){const n=e[t];if(tn(n,"Missing node"),w_e(n))return n}return null}function SF(e){return e&&Number(getComputedStyle(e).zIndex)||0}function _F(e){const t=[];for(;e;)t.push(e),e=wW(e);return t}function wW(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const xW=1,EW=2,SW=4,_W=8,x_e=h_e()==="coarse";let Bo=[],ad=!1,Yi=new Map,Fw=new Map;const Pm=new Set;function E_e(e,t,n,r,a){var o;const{ownerDocument:i}=t,l={direction:n,element:t,hitAreaMargins:r,setResizeHandlerState:a},u=(o=Yi.get(i))!==null&&o!==void 0?o:0;return Yi.set(i,u+1),Pm.add(l),wv(),function(){var m;Fw.delete(e),Pm.delete(l);const h=(m=Yi.get(i))!==null&&m!==void 0?m:1;if(Yi.set(i,h-1),wv(),h===1&&Yi.delete(i),Bo.includes(l)){const g=Bo.indexOf(l);g>=0&&Bo.splice(g,1),Bw(),a("up",!0,null)}}}function S_e(e){const{target:t}=e,{x:n,y:r}=zw(e);ad=!0,WO({target:t,x:n,y:r}),wv(),Bo.length>0&&(xv("down",e),Bw(),e.preventDefault(),TW(t)||e.stopImmediatePropagation())}function xS(e){const{x:t,y:n}=zw(e);if(ad&&e.type!=="pointerleave"&&e.buttons===0&&(ad=!1,xv("up",e)),!ad){const{target:r}=e;WO({target:r,x:t,y:n})}xv("move",e),Bw(),Bo.length>0&&e.preventDefault()}function ES(e){const{target:t}=e,{x:n,y:r}=zw(e);Fw.clear(),ad=!1,Bo.length>0&&(e.preventDefault(),TW(t)||e.stopImmediatePropagation()),xv("up",e),WO({target:t,x:n,y:r}),Bw(),wv()}function TW(e){let t=e;for(;t;){if(t.hasAttribute(br.resizeHandle))return!0;t=t.parentElement}return!1}function WO({target:e,x:t,y:n}){Bo.splice(0);let r=null;(e instanceof HTMLElement||e instanceof SVGElement)&&(r=e),Pm.forEach(a=>{const{element:o,hitAreaMargins:i}=a,l=o.getBoundingClientRect(),{bottom:u,left:f,right:m,top:h}=l,g=x_e?i.coarse:i.fine;if(t>=f-g&&t<=m+g&&n>=h-g&&n<=u+g){if(r!==null&&document.contains(r)&&o!==r&&!o.contains(r)&&!r.contains(o)&&b_e(r,o)>0){let E=r,x=!1;for(;E&&!E.contains(o);){if(g_e(E.getBoundingClientRect(),l)){x=!0;break}E=E.parentElement}if(x)return}Bo.push(a)}})}function SS(e,t){Fw.set(e,t)}function Bw(){let e=!1,t=!1;Bo.forEach(r=>{const{direction:a}=r;a==="horizontal"?e=!0:t=!0});let n=0;Fw.forEach(r=>{n|=r}),e&&t?wS("intersection",n):e?wS("horizontal",n):t?wS("vertical",n):m_e()}let _S;function wv(){var e;(e=_S)===null||e===void 0||e.abort(),_S=new AbortController;const t={capture:!0,signal:_S.signal};Pm.size&&(ad?(Bo.length>0&&Yi.forEach((n,r)=>{const{body:a}=r;n>0&&(a.addEventListener("contextmenu",ES,t),a.addEventListener("pointerleave",xS,t),a.addEventListener("pointermove",xS,t))}),Yi.forEach((n,r)=>{const{body:a}=r;a.addEventListener("pointerup",ES,t),a.addEventListener("pointercancel",ES,t)})):Yi.forEach((n,r)=>{const{body:a}=r;n>0&&(a.addEventListener("pointerdown",S_e,t),a.addEventListener("pointermove",xS,t))}))}function xv(e,t){Pm.forEach(n=>{const{setResizeHandlerState:r}=n,a=Bo.includes(n);r(e,a,t)})}function __e(){const[e,t]=y.useState(0);return y.useCallback(()=>t(n=>n+1),[])}function tn(e,t){if(!e)throw console.error(t),Error(t)}function vc(e,t,n=VO){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function Ws(e,t,n=VO){return vc(e,t,n)===0}function Qa(e,t,n){return vc(e,t,n)===0}function T_e(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++){const a=e[r],o=t[r];if(!Qa(a,o,n))return!1}return!0}function Wu({panelConstraints:e,panelIndex:t,size:n}){const r=e[t];tn(r!=null,`Panel constraints not found for index ${t}`);let{collapsedSize:a=0,collapsible:o,maxSize:i=100,minSize:l=0}=r;if(vc(n,l)<0)if(o){const u=(a+l)/2;vc(n,u)<0?n=a:n=l}else n=l;return n=Math.min(i,n),n=parseFloat(n.toFixed(VO)),n}function Lp({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:r,prevLayout:a,trigger:o}){if(Qa(e,0))return t;const i=[...t],[l,u]=r;tn(l!=null,"Invalid first pivot index"),tn(u!=null,"Invalid second pivot index");let f=0;if(o==="keyboard"){{const h=e<0?u:l,g=n[h];tn(g,`Panel constraints not found for index ${h}`);const{collapsedSize:b=0,collapsible:E,minSize:x=0}=g;if(E){const w=t[h];if(tn(w!=null,`Previous layout not found for panel index ${h}`),Qa(w,b)){const S=x-w;vc(S,Math.abs(e))>0&&(e=e<0?0-S:S)}}}{const h=e<0?l:u,g=n[h];tn(g,`No panel constraints found for index ${h}`);const{collapsedSize:b=0,collapsible:E,minSize:x=0}=g;if(E){const w=t[h];if(tn(w!=null,`Previous layout not found for panel index ${h}`),Qa(w,x)){const S=w-b;vc(S,Math.abs(e))>0&&(e=e<0?0-S:S)}}}}{const h=e<0?1:-1;let g=e<0?u:l,b=0;for(;;){const x=t[g];tn(x!=null,`Previous layout not found for panel index ${g}`);const S=Wu({panelConstraints:n,panelIndex:g,size:100})-x;if(b+=S,g+=h,g<0||g>=n.length)break}const E=Math.min(Math.abs(e),Math.abs(b));e=e<0?0-E:E}{let g=e<0?l:u;for(;g>=0&&g<n.length;){const b=Math.abs(e)-Math.abs(f),E=t[g];tn(E!=null,`Previous layout not found for panel index ${g}`);const x=E-b,w=Wu({panelConstraints:n,panelIndex:g,size:x});if(!Qa(E,w)&&(f+=E-w,i[g]=w,f.toFixed(3).localeCompare(Math.abs(e).toFixed(3),void 0,{numeric:!0})>=0))break;e<0?g--:g++}}if(T_e(a,i))return a;{const h=e<0?u:l,g=t[h];tn(g!=null,`Previous layout not found for panel index ${h}`);const b=g+f,E=Wu({panelConstraints:n,panelIndex:h,size:b});if(i[h]=E,!Qa(E,b)){let x=b-E,S=e<0?u:l;for(;S>=0&&S<n.length;){const _=i[S];tn(_!=null,`Previous layout not found for panel index ${S}`);const T=_+x,k=Wu({panelConstraints:n,panelIndex:S,size:T});if(Qa(_,k)||(x-=k-_,i[S]=k),Qa(x,0))break;e>0?S--:S++}}}const m=i.reduce((h,g)=>g+h,0);return Qa(m,100)?i:a}function N_e({layout:e,panelsArray:t,pivotIndices:n}){let r=0,a=100,o=0,i=0;const l=n[0];tn(l!=null,"No pivot index found"),t.forEach((h,g)=>{const{constraints:b}=h,{maxSize:E=100,minSize:x=0}=b;g===l?(r=x,a=E):(o+=x,i+=E)});const u=Math.min(a,100-o),f=Math.max(r,100-i),m=e[l];return{valueMax:u,valueMin:f,valueNow:m}}function $m(e,t=document){return Array.from(t.querySelectorAll(`[${br.resizeHandleId}][data-panel-group-id="${e}"]`))}function NW(e,t,n=document){const a=$m(e,n).findIndex(o=>o.getAttribute(br.resizeHandleId)===t);return a??null}function CW(e,t,n){const r=NW(e,t,n);return r!=null?[r,r+1]:[-1,-1]}function C_e(e){return e instanceof HTMLElement?!0:typeof e=="object"&&e!==null&&"tagName"in e&&"getAttribute"in e}function RW(e,t=document){if(C_e(t)&&t.dataset.panelGroupId==e)return t;const n=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return n||null}function Hw(e,t=document){const n=t.querySelector(`[${br.resizeHandleId}="${e}"]`);return n||null}function R_e(e,t,n,r=document){var a,o,i,l;const u=Hw(t,r),f=$m(e,r),m=u?f.indexOf(u):-1,h=(a=(o=n[m])===null||o===void 0?void 0:o.id)!==null&&a!==void 0?a:null,g=(i=(l=n[m+1])===null||l===void 0?void 0:l.id)!==null&&i!==void 0?i:null;return[h,g]}function k_e({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:r,panelDataArray:a,panelGroupElement:o,setLayout:i}){y.useRef({didWarnAboutMissingResizeHandle:!1}),ic(()=>{if(!o)return;const l=$m(n,o);for(let u=0;u<a.length-1;u++){const{valueMax:f,valueMin:m,valueNow:h}=N_e({layout:r,panelsArray:a,pivotIndices:[u,u+1]}),g=l[u];if(g!=null){const b=a[u];tn(b,`No panel data found for index "${u}"`),g.setAttribute("aria-controls",b.id),g.setAttribute("aria-valuemax",""+Math.round(f)),g.setAttribute("aria-valuemin",""+Math.round(m)),g.setAttribute("aria-valuenow",h!=null?""+Math.round(h):"")}}return()=>{l.forEach((u,f)=>{u.removeAttribute("aria-controls"),u.removeAttribute("aria-valuemax"),u.removeAttribute("aria-valuemin"),u.removeAttribute("aria-valuenow")})}},[n,r,a,o]),y.useEffect(()=>{if(!o)return;const l=t.current;tn(l,"Eager values not found");const{panelDataArray:u}=l,f=RW(n,o);tn(f!=null,`No group found for id "${n}"`);const m=$m(n,o);tn(m,`No resize handles found for group id "${n}"`);const h=m.map(g=>{const b=g.getAttribute(br.resizeHandleId);tn(b,"Resize handle element has no handle id attribute");const[E,x]=R_e(n,b,u,o);if(E==null||x==null)return()=>{};const w=S=>{if(!S.defaultPrevented)switch(S.key){case"Enter":{S.preventDefault();const _=u.findIndex(T=>T.id===E);if(_>=0){const T=u[_];tn(T,`No panel data found for index ${_}`);const k=r[_],{collapsedSize:R=0,collapsible:A,minSize:C=0}=T.constraints;if(k!=null&&A){const O=Lp({delta:Qa(k,R)?C-R:R-k,initialLayout:r,panelConstraints:u.map(M=>M.constraints),pivotIndices:CW(n,b,o),prevLayout:r,trigger:"keyboard"});r!==O&&i(O)}}break}}};return g.addEventListener("keydown",w),()=>{g.removeEventListener("keydown",w)}});return()=>{h.forEach(g=>g())}},[o,e,t,n,r,a,i])}function TF(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function kW(e,t){const n=e==="horizontal",{x:r,y:a}=zw(t);return n?r:a}function A_e(e,t,n,r,a){const o=n==="horizontal",i=Hw(t,a);tn(i,`No resize handle element found for id "${t}"`);const l=i.getAttribute(br.groupId);tn(l,"Resize handle element has no group id attribute");let{initialCursorPosition:u}=r;const f=kW(n,e),m=RW(l,a);tn(m,`No group element found for id "${l}"`);const h=m.getBoundingClientRect(),g=o?h.width:h.height;return(f-u)/g*100}function I_e(e,t,n,r,a,o){if(bW(e)){const i=n==="horizontal";let l=0;e.shiftKey?l=100:a!=null?l=a:l=10;let u=0;switch(e.key){case"ArrowDown":u=i?0:l;break;case"ArrowLeft":u=i?-l:0;break;case"ArrowRight":u=i?l:0;break;case"ArrowUp":u=i?0:-l;break;case"End":u=100;break;case"Home":u=-100;break}return u}else return r==null?0:A_e(e,t,n,r,o)}function O_e({panelDataArray:e}){const t=Array(e.length),n=e.map(o=>o.constraints);let r=0,a=100;for(let o=0;o<e.length;o++){const i=n[o];tn(i,`Panel constraints not found for index ${o}`);const{defaultSize:l}=i;l!=null&&(r++,t[o]=l,a-=l)}for(let o=0;o<e.length;o++){const i=n[o];tn(i,`Panel constraints not found for index ${o}`);const{defaultSize:l}=i;if(l!=null)continue;const u=e.length-r,f=a/u;r++,t[o]=f,a-=f}return t}function vu(e,t,n){t.forEach((r,a)=>{const o=e[a];tn(o,`Panel data not found for index ${a}`);const{callbacks:i,constraints:l,id:u}=o,{collapsedSize:f=0,collapsible:m}=l,h=n[u];if(h==null||r!==h){n[u]=r;const{onCollapse:g,onExpand:b,onResize:E}=i;E&&E(r,h),m&&(g||b)&&(b&&(h==null||Ws(h,f))&&!Ws(r,f)&&b(),g&&(h==null||!Ws(h,f))&&Ws(r,f)&&g())}})}function Wb(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!=t[n])return!1;return!0}function D_e({defaultSize:e,dragState:t,layout:n,panelData:r,panelIndex:a,precision:o=3}){const i=n[a];let l;return i==null?l=e!=null?e.toFixed(o):"1":r.length===1?l="1":l=i.toFixed(o),{flexBasis:0,flexGrow:l,flexShrink:1,overflow:"hidden",pointerEvents:t!==null?"none":void 0}}function L_e(e,t=10){let n=null;return(...a)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...a)},t)}}function NF(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function AW(e){return`react-resizable-panels:${e}`}function IW(e){return e.map(t=>{const{constraints:n,id:r,idIsFromProps:a,order:o}=t;return a?r:o?`${o}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function OW(e,t){try{const n=AW(e),r=t.getItem(n);if(r){const a=JSON.parse(r);if(typeof a=="object"&&a!=null)return a}}catch{}return null}function M_e(e,t,n){var r,a;const o=(r=OW(e,n))!==null&&r!==void 0?r:{},i=IW(t);return(a=o[i])!==null&&a!==void 0?a:null}function j_e(e,t,n,r,a){var o;const i=AW(e),l=IW(t),u=(o=OW(e,a))!==null&&o!==void 0?o:{};u[l]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{a.setItem(i,JSON.stringify(u))}catch(f){console.error(f)}}function CF({layout:e,panelConstraints:t}){const n=[...e],r=n.reduce((o,i)=>o+i,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(o=>`${o}%`).join(", ")}`);if(!Qa(r,100)&&n.length>0)for(let o=0;o<t.length;o++){const i=n[o];tn(i!=null,`No layout data found for index ${o}`);const l=100/r*i;n[o]=l}let a=0;for(let o=0;o<t.length;o++){const i=n[o];tn(i!=null,`No layout data found for index ${o}`);const l=Wu({panelConstraints:t,panelIndex:o,size:i});i!=l&&(a+=i-l,n[o]=l)}if(!Qa(a,0))for(let o=0;o<t.length;o++){const i=n[o];tn(i!=null,`No layout data found for index ${o}`);const l=i+a,u=Wu({panelConstraints:t,panelIndex:o,size:l});if(i!==u&&(a-=u-i,n[o]=u,Qa(a,0)))break}return n}const P_e=100,Mp={getItem:e=>(NF(Mp),Mp.getItem(e)),setItem:(e,t)=>{NF(Mp),Mp.setItem(e,t)}},RF={};function DW({autoSaveId:e=null,children:t,className:n="",direction:r,forwardedRef:a,id:o=null,onLayout:i=null,keyboardResizeBy:l=null,storage:u=Mp,style:f,tagName:m="div",...h}){const g=GO(o),b=y.useRef(null),[E,x]=y.useState(null),[w,S]=y.useState([]),_=__e(),T=y.useRef({}),k=y.useRef(new Map),R=y.useRef(0),A=y.useRef({autoSaveId:e,direction:r,dragState:E,id:g,keyboardResizeBy:l,onLayout:i,storage:u}),C=y.useRef({layout:w,panelDataArray:[],panelDataArrayChanged:!1});y.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),y.useImperativeHandle(a,()=>({getId:()=>A.current.id,getLayout:()=>{const{layout:U}=C.current;return U},setLayout:U=>{const{onLayout:D}=A.current,{layout:$,panelDataArray:G}=C.current,W=CF({layout:U,panelConstraints:G.map(re=>re.constraints)});TF($,W)||(S(W),C.current.layout=W,D&&D(W),vu(G,W,T.current))}}),[]),ic(()=>{A.current.autoSaveId=e,A.current.direction=r,A.current.dragState=E,A.current.id=g,A.current.onLayout=i,A.current.storage=u}),k_e({committedValuesRef:A,eagerValuesRef:C,groupId:g,layout:w,panelDataArray:C.current.panelDataArray,setLayout:S,panelGroupElement:b.current}),y.useEffect(()=>{const{panelDataArray:U}=C.current;if(e){if(w.length===0||w.length!==U.length)return;let D=RF[e];D==null&&(D=L_e(j_e,P_e),RF[e]=D);const $=[...U],G=new Map(k.current);D(e,$,G,w,u)}},[e,w,u]),y.useEffect(()=>{});const O=y.useCallback(U=>{const{onLayout:D}=A.current,{layout:$,panelDataArray:G}=C.current;if(U.constraints.collapsible){const W=G.map(ne=>ne.constraints),{collapsedSize:re=0,panelSize:pe,pivotIndices:me}=Wl(G,U,$);if(tn(pe!=null,`Panel size not found for panel "${U.id}"`),!Ws(pe,re)){k.current.set(U.id,pe);const J=ku(G,U)===G.length-1?pe-re:re-pe,X=Lp({delta:J,initialLayout:$,panelConstraints:W,pivotIndices:me,prevLayout:$,trigger:"imperative-api"});Wb($,X)||(S(X),C.current.layout=X,D&&D(X),vu(G,X,T.current))}}},[]),M=y.useCallback((U,D)=>{const{onLayout:$}=A.current,{layout:G,panelDataArray:W}=C.current;if(U.constraints.collapsible){const re=W.map(se=>se.constraints),{collapsedSize:pe=0,panelSize:me=0,minSize:ne=0,pivotIndices:J}=Wl(W,U,G),X=D??ne;if(Ws(me,pe)){const se=k.current.get(U.id),he=se!=null&&se>=X?se:X,Be=ku(W,U)===W.length-1?me-he:he-me,$e=Lp({delta:Be,initialLayout:G,panelConstraints:re,pivotIndices:J,prevLayout:G,trigger:"imperative-api"});Wb(G,$e)||(S($e),C.current.layout=$e,$&&$($e),vu(W,$e,T.current))}}},[]),L=y.useCallback(U=>{const{layout:D,panelDataArray:$}=C.current,{panelSize:G}=Wl($,U,D);return tn(G!=null,`Panel size not found for panel "${U.id}"`),G},[]),j=y.useCallback((U,D)=>{const{panelDataArray:$}=C.current,G=ku($,U);return D_e({defaultSize:D,dragState:E,layout:w,panelData:$,panelIndex:G})},[E,w]),B=y.useCallback(U=>{const{layout:D,panelDataArray:$}=C.current,{collapsedSize:G=0,collapsible:W,panelSize:re}=Wl($,U,D);return tn(re!=null,`Panel size not found for panel "${U.id}"`),W===!0&&Ws(re,G)},[]),K=y.useCallback(U=>{const{layout:D,panelDataArray:$}=C.current,{collapsedSize:G=0,collapsible:W,panelSize:re}=Wl($,U,D);return tn(re!=null,`Panel size not found for panel "${U.id}"`),!W||vc(re,G)>0},[]),Z=y.useCallback(U=>{const{panelDataArray:D}=C.current;D.push(U),D.sort(($,G)=>{const W=$.order,re=G.order;return W==null&&re==null?0:W==null?-1:re==null?1:W-re}),C.current.panelDataArrayChanged=!0,_()},[_]);ic(()=>{if(C.current.panelDataArrayChanged){C.current.panelDataArrayChanged=!1;const{autoSaveId:U,onLayout:D,storage:$}=A.current,{layout:G,panelDataArray:W}=C.current;let re=null;if(U){const me=M_e(U,W,$);me&&(k.current=new Map(Object.entries(me.expandToSizes)),re=me.layout)}re==null&&(re=O_e({panelDataArray:W}));const pe=CF({layout:re,panelConstraints:W.map(me=>me.constraints)});TF(G,pe)||(S(pe),C.current.layout=pe,D&&D(pe),vu(W,pe,T.current))}}),ic(()=>{const U=C.current;return()=>{U.layout=[]}},[]);const te=y.useCallback(U=>{let D=!1;const $=b.current;return $&&window.getComputedStyle($,null).getPropertyValue("direction")==="rtl"&&(D=!0),function(W){W.preventDefault();const re=b.current;if(!re)return()=>null;const{direction:pe,dragState:me,id:ne,keyboardResizeBy:J,onLayout:X}=A.current,{layout:se,panelDataArray:he}=C.current,{initialLayout:Te}=me??{},Be=CW(ne,U,re);let $e=I_e(W,U,pe,me,J,re);const Ge=pe==="horizontal";Ge&&D&&($e=-$e);const dt=he.map(rt=>rt.constraints),Ve=Lp({delta:$e,initialLayout:Te??se,panelConstraints:dt,pivotIndices:Be,prevLayout:se,trigger:bW(W)?"keyboard":"mouse-or-touch"}),ct=!Wb(se,Ve);(yW(W)||vW(W))&&R.current!=$e&&(R.current=$e,!ct&&$e!==0?Ge?SS(U,$e<0?xW:EW):SS(U,$e<0?SW:_W):SS(U,0)),ct&&(S(Ve),C.current.layout=Ve,X&&X(Ve),vu(he,Ve,T.current))}},[]),V=y.useCallback((U,D)=>{const{onLayout:$}=A.current,{layout:G,panelDataArray:W}=C.current,re=W.map(se=>se.constraints),{panelSize:pe,pivotIndices:me}=Wl(W,U,G);tn(pe!=null,`Panel size not found for panel "${U.id}"`);const J=ku(W,U)===W.length-1?pe-D:D-pe,X=Lp({delta:J,initialLayout:G,panelConstraints:re,pivotIndices:me,prevLayout:G,trigger:"imperative-api"});Wb(G,X)||(S(X),C.current.layout=X,$&&$(X),vu(W,X,T.current))},[]),Y=y.useCallback((U,D)=>{const{layout:$,panelDataArray:G}=C.current,{collapsedSize:W=0,collapsible:re}=D,{collapsedSize:pe=0,collapsible:me,maxSize:ne=100,minSize:J=0}=U.constraints,{panelSize:X}=Wl(G,U,$);X!=null&&(re&&me&&Ws(X,W)?Ws(W,pe)||V(U,pe):X<J?V(U,J):X>ne&&V(U,ne))},[V]),F=y.useCallback((U,D)=>{const{direction:$}=A.current,{layout:G}=C.current;if(!b.current)return;const W=Hw(U,b.current);tn(W,`Drag handle element not found for id "${U}"`);const re=kW($,D);x({dragHandleId:U,dragHandleRect:W.getBoundingClientRect(),initialCursorPosition:re,initialLayout:G})},[]),ae=y.useCallback(()=>{x(null)},[]),ee=y.useCallback(U=>{const{panelDataArray:D}=C.current,$=ku(D,U);$>=0&&(D.splice($,1),delete T.current[U.id],C.current.panelDataArrayChanged=!0,_())},[_]),P=y.useMemo(()=>({collapsePanel:O,direction:r,dragState:E,expandPanel:M,getPanelSize:L,getPanelStyle:j,groupId:g,isPanelCollapsed:B,isPanelExpanded:K,reevaluatePanelConstraints:Y,registerPanel:Z,registerResizeHandle:te,resizePanel:V,startDragging:F,stopDragging:ae,unregisterPanel:ee,panelGroupElement:b.current}),[O,E,r,M,L,j,g,B,K,Y,Z,te,V,F,ae,ee]),H={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return y.createElement(Uw.Provider,{value:P},y.createElement(m,{...h,children:t,className:n,id:o,ref:b,style:{...H,...f},[br.group]:"",[br.groupDirection]:r,[br.groupId]:g}))}const LW=y.forwardRef((e,t)=>y.createElement(DW,{...e,forwardedRef:t}));DW.displayName="PanelGroup";LW.displayName="forwardRef(PanelGroup)";function ku(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function Wl(e,t,n){const r=ku(e,t),o=r===e.length-1?[r-1,r]:[r,r+1],i=n[r];return{...t.constraints,panelSize:i,pivotIndices:o}}function $_e({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:r}){y.useEffect(()=>{if(e||n==null||r==null)return;const a=Hw(t,r);if(a==null)return;const o=i=>{if(!i.defaultPrevented)switch(i.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{i.preventDefault(),n(i);break}case"F6":{i.preventDefault();const l=a.getAttribute(br.groupId);tn(l,`No group element found for id "${l}"`);const u=$m(l,r),f=NW(l,t,r);tn(f!==null,`No resize element found for id "${t}"`);const m=i.shiftKey?f>0?f-1:u.length-1:f+1<u.length?f+1:0;u[m].focus();break}}};return a.addEventListener("keydown",o),()=>{a.removeEventListener("keydown",o)}},[r,e,t,n])}function MW({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:r,id:a,onBlur:o,onClick:i,onDragging:l,onFocus:u,onPointerDown:f,onPointerUp:m,style:h={},tabIndex:g=0,tagName:b="div",...E}){var x,w;const S=y.useRef(null),_=y.useRef({onClick:i,onDragging:l,onPointerDown:f,onPointerUp:m});y.useEffect(()=>{_.current.onClick=i,_.current.onDragging=l,_.current.onPointerDown=f,_.current.onPointerUp=m});const T=y.useContext(Uw);if(T===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:k,groupId:R,registerResizeHandle:A,startDragging:C,stopDragging:O,panelGroupElement:M}=T,L=GO(a),[j,B]=y.useState("inactive"),[K,Z]=y.useState(!1),[te,V]=y.useState(null),Y=y.useRef({state:j});ic(()=>{Y.current.state=j}),y.useEffect(()=>{if(n)V(null);else{const P=A(L);V(()=>P)}},[n,L,A]);const F=(x=r?.coarse)!==null&&x!==void 0?x:15,ae=(w=r?.fine)!==null&&w!==void 0?w:5;y.useEffect(()=>{if(n||te==null)return;const P=S.current;tn(P,"Element ref not attached");let H=!1;return E_e(L,P,k,{coarse:F,fine:ae},(D,$,G)=>{if(!$){B("inactive");return}switch(D){case"down":{B("drag"),H=!1,tn(G,'Expected event to be defined for "down" action'),C(L,G);const{onDragging:W,onPointerDown:re}=_.current;W?.(!0),re?.();break}case"move":{const{state:W}=Y.current;H=!0,W!=="drag"&&B("hover"),tn(G,'Expected event to be defined for "move" action'),te(G);break}case"up":{B("hover"),O();const{onClick:W,onDragging:re,onPointerUp:pe}=_.current;re?.(!1),pe?.(),H||W?.();break}}})},[F,k,n,ae,A,L,te,C,O]),$_e({disabled:n,handleId:L,resizeHandler:te,panelGroupElement:M});const ee={touchAction:"none",userSelect:"none"};return y.createElement(b,{...E,children:e,className:t,id:a,onBlur:()=>{Z(!1),o?.()},onFocus:()=>{Z(!0),u?.()},ref:S,role:"separator",style:{...ee,...h},tabIndex:g,[br.groupDirection]:k,[br.groupId]:R,[br.resizeHandle]:"",[br.resizeHandleActive]:j==="drag"?"pointer":K?"keyboard":void 0,[br.resizeHandleEnabled]:!n,[br.resizeHandleId]:L,[br.resizeHandleState]:j})}MW.displayName="PanelResizeHandle";function Ta({className:e,...t}){return d.jsx(LW,{"data-slot":"resizable-panel-group",className:Ue("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t})}function Yn({...e}){return d.jsx(gW,{"data-slot":"resizable-panel",...e})}function Ho({withHandle:e,className:t,...n}){return d.jsx(MW,{"data-slot":"resizable-handle",className:Ue("bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...n,children:e&&d.jsx("div",{className:"bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border",children:d.jsx(Uue,{className:"size-2.5"})})})}function xh({className:e,...t}){return d.jsx("kbd",{"data-slot":"kbd",className:Ue("bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none","[&_svg:not([class*='size-'])]:size-3","[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",e),...t})}function U_e({isSearchExpanded:e,searchQuery:t,filteredNotificationsCount:n,notificationsCount:r,onSearchExpand:a,onSearchChange:o,onSearchBlur:i,onClearAll:l,searchInputRef:u}){return d.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[d.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?d.jsx(Hn,{ref:u,placeholder:"Search notifications...",value:t,onChange:f=>o(f.target.value),onBlur:i,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Notifications"}),d.jsx(Pr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:d.jsx(sf,{className:"h-4 w-4"})})}),d.jsxs(Yt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(xh,{children:"F"})]})]})]})}),d.jsx("div",{className:"flex items-center gap-2",children:d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:l,disabled:r===0,className:"h-8 w-8 p-0",children:d.jsx(ni,{className:"h-4 w-4"})})}),d.jsx(Yt,{side:"bottom",children:"Clear all"})]})})]})}function El({id:e,isSelected:t,isFocused:n,icon:r,title:a,description:o,metadata:i,onClick:l,className:u}){return d.jsx("button",{id:e,type:"button",onClick:l,className:Ue("w-full text-left cursor-pointer p-2 sm:p-4 border-b dark:border-zinc-700 hover:bg-gray-50 dark:hover:bg-zinc-800/50 transition-colors group",t&&"bg-zinc-50 dark:bg-zinc-800 border-l-4 border-l-zinc-500",n&&"ring-2 ring-zinc-500 dark:ring-zinc-400 ring-inset",u),children:d.jsxs("div",{className:"flex items-start gap-2 sm:gap-3",children:[r&&d.jsx("div",{className:"flex-shrink-0 mt-1",children:d.jsx("div",{className:Ue("p-2.5 rounded-full transition-colors",t?"bg-zinc-500 dark:bg-zinc-100/80 text-zinc-100 dark:text-zinc-900":"bg-gray-100 dark:bg-zinc-700 text-gray-600 dark:text-gray-400 group-hover:bg-gray-200 dark:group-hover:bg-zinc-600"),children:r})}),d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsx("div",{className:"flex items-center gap-2 mb-1",children:d.jsx("h3",{className:Ue("font-medium truncate font-mono text-sm"),children:a})}),o&&d.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 line-clamp-2",children:o})]})]})})}function z_e({notifications:e,selectedNotification:t,onNotificationSelect:n,focusedIndex:r,formatRelativeTime:a,listRef:o}){return e.length===0?d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx(of,{vertical:!0,noBorder:!0,message:"No notifications yet"})}):d.jsx("div",{ref:o,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((i,l)=>d.jsx(El,{id:`notification-${i.id}`,isSelected:t?.id===i.id,isFocused:r===l,title:d.jsxs("span",{className:"flex items-center gap-3",children:[i.method,!i.read&&d.jsx("span",{className:"size-1.5 block rounded-full bg-orange-500"})]}),description:(()=>{const u=a(i.timestamp),f=i.params&&Object.keys(i.params).length>0?Object.keys(i.params).length:0,m=f>0?` | ${f} param${f>1?"s":""}`:"";return u+m})(),onClick:()=>n(i)},i.id))})}function F_e({notification:e,previewMode:t,onTogglePreview:n,onCopy:r,onDownload:a,onFullscreen:o,isCopied:i=!1,onClose:l}){return e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:"flex-shrink-0 px-4 py-3 border-b border-gray-200 dark:border-zinc-700 flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(um,{className:"h-3 w-3 text-gray-400"}),d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleTimeString()})]}),d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:e.formatRelativeTime(e.timestamp)})]}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsxs(Me,{variant:"ghost",size:"sm",onClick:n,className:t?"":"text-purple-600 dark:text-purple-400",children:[t?d.jsx(YN,{className:"h-4 w-4 mr-1"}):d.jsx(UH,{className:"h-4 w-4 mr-1"}),t?"JSON":"Formatted"]}),d.jsx(Me,{variant:"ghost",size:"sm",onClick:r,children:i?d.jsx(Or,{className:"h-4 w-4"}):d.jsx(wr,{className:"h-4 w-4"})}),d.jsx(Me,{variant:"ghost",size:"sm",onClick:a,children:d.jsx(th,{className:"h-4 w-4"})}),d.jsx(Me,{variant:"ghost",size:"sm",onClick:o,children:d.jsx(fm,{className:"h-4 w-4"})}),l&&d.jsx(Me,{variant:"ghost",size:"sm",onClick:l,children:d.jsx(vs,{className:"h-4 w-4"})})]})]}),d.jsx("div",{className:"flex-1 overflow-y-auto",children:d.jsx("div",{className:"px-4 pt-4",children:d.jsx(yr,{data:{method:e.method,timestamp:e.timestamp,read:e.read,params:e.params},filename:`notification-${e.method.replace(/[^a-zA-Z0-9]/g,"-")}-${Date.now()}.json`})})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(KN,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select a notification to view details"})]})}function Ev(e){const n=Date.now()-e,r=Math.floor(n/1e3),a=Math.floor(r/60),o=Math.floor(a/60),i=Math.floor(o/24);return r<60?"just now":a<60?`${a}m ago`:o<24?`${o}h ago`:i<7?`${i}d ago`:new Date(e).toLocaleDateString()}function B_e({notifications:e,unreadCount:t,markNotificationRead:n,markAllNotificationsRead:r,clearNotifications:a,serverId:o,isConnected:i}){const[l,u]=y.useState(null),[f,m]=y.useState(""),[h,g]=y.useState(-1),[b,E]=y.useState(!0),[x,w]=y.useState(!1),[S,_]=y.useState(!0),[T,k]=y.useState(!1),R=y.useRef(null),A=y.useRef(null),C=y.useRef(null),O=y.useRef(!1);y.useEffect(()=>{b&&e.length>0&&R.current&&!O.current&&(R.current.scrollTop=0)},[e.length,b]),y.useEffect(()=>{const Y=R.current;if(!Y)return;const F=()=>{Y.scrollTop>0&&(O.current=!0,E(!1))};return Y.addEventListener("scroll",F),()=>Y.removeEventListener("scroll",F)},[]),y.useEffect(()=>{e.length===0&&(O.current=!1,E(!0))},[e.length]),y.useEffect(()=>{l&&!l.read&&n(l.id)},[l,n]),y.useEffect(()=>{x&&C.current&&C.current.focus()},[x]);const M=y.useCallback(()=>{f.trim()||w(!1)},[f]),L=y.useMemo(()=>{if(!f.trim())return e;const Y=f.toLowerCase();return e.filter(F=>F.method.toLowerCase().includes(Y)||JSON.stringify(F.params||{}).toLowerCase().includes(Y))},[e,f]);y.useEffect(()=>{g(-1)},[f]),y.useEffect(()=>{const Y=F=>{const ae=F.target;if(ae.tagName==="INPUT"||ae.tagName==="TEXTAREA"||ae.contentEditable==="true"||F.metaKey||F.ctrlKey||F.altKey)return;const P=L;if(F.key==="ArrowDown")F.preventDefault(),g(H=>{const U=H+1;return U>=P.length?0:U});else if(F.key==="ArrowUp")F.preventDefault(),g(H=>{const U=H-1;return U<0?P.length-1:U});else if(F.key==="Enter"&&h>=0){F.preventDefault();const H=L[h];H&&j(H)}};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[h,L]),y.useEffect(()=>{if(h>=0){const Y=`notification-${L[h]?.id}`,F=document.getElementById(Y);F&&F.scrollIntoView({behavior:"smooth",block:"nearest"})}},[h,L]);const j=y.useCallback(Y=>{u(Y)},[]),B=y.useCallback(()=>{window.confirm("Are you sure you want to clear all notifications? This cannot be undone.")&&(a(),u(null))},[a]),K=y.useCallback(async()=>{if(l)try{await navigator.clipboard.writeText(JSON.stringify({method:l.method,timestamp:l.timestamp,read:l.read,params:l.params},null,2)),k(!0),setTimeout(()=>k(!1),2e3)}catch(Y){console.error("[NotificationsTab] Failed to copy notification:",Y)}},[l]),Z=y.useCallback(()=>{if(l)try{const Y=new globalThis.Blob([JSON.stringify({method:l.method,timestamp:l.timestamp,read:l.read,params:l.params},null,2)],{type:"application/json"}),F=URL.createObjectURL(Y),ae=document.createElement("a");ae.href=F,ae.download=`notification-${Date.now()}.json`,document.body.appendChild(ae),ae.click(),document.body.removeChild(ae),URL.revokeObjectURL(F)}catch(Y){console.error("[NotificationsTab] Failed to download notification:",Y)}},[l]),te=y.useCallback(async()=>{if(A.current)try{document.fullscreenElement?await document.exitFullscreen():await A.current.requestFullscreen()}catch(Y){console.error("[NotificationsTab] Failed to toggle fullscreen:",Y)}},[]),V=l?{method:l.method,params:l.params,timestamp:l.timestamp,read:l.read,formatRelativeTime:Ev}:null;return i?d.jsxs(Ta,{direction:"horizontal",className:"h-full",children:[d.jsx(Yn,{defaultSize:40,minSize:30,children:d.jsx(Ta,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:d.jsxs(Yn,{defaultSize:75,minSize:30,children:[d.jsx(U_e,{isSearchExpanded:x,searchQuery:f,filteredNotificationsCount:L.length,notificationsCount:e.length,onSearchExpand:()=>w(!0),onSearchChange:m,onSearchBlur:M,onClearAll:B,searchInputRef:C}),d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(z_e,{notifications:L,selectedNotification:l,onNotificationSelect:j,focusedIndex:h,formatRelativeTime:Ev,listRef:R})})]})})}),d.jsx(Ho,{}),d.jsx(Yn,{defaultSize:60,minSize:40,children:d.jsx("div",{ref:A,className:"h-full bg-white dark:bg-zinc-900",children:d.jsx(F_e,{notification:V,previewMode:S,onTogglePreview:()=>_(!S),onCopy:K,onDownload:Z,onFullscreen:te,onClose:()=>u(null),isCopied:T})})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(KN,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function KO({serverIds:e,onCountChange:t,onClearRef:n}={}){const[r,a]=y.useState([]),o=y.useRef(null),[i,l]=y.useState(new Set),[u]=y.useState(""),f=b=>{l(E=>{const x=new Set(E);return x.has(b)?x.delete(b):x.add(b),x})},m=async()=>{a([]),l(new Set),t?.(0),e&&e.length>0?e.forEach(b=>Uy(b)):Uy()},h=y.useMemo(()=>!e||e.length===0?"":[...e].sort().join(","),[e]);y.useEffect(()=>(n&&(n.current=m),()=>{n&&(n.current=null)}),[n,m]),y.useEffect(()=>{t?.(r.length)},[r.length,t]),y.useEffect(()=>{console.log("[RPC Logger] Subscribing to RPC logs for servers:",e);const b=SN(),x=(e&&e.length>0?b.filter(S=>e.includes(S.serverId)):b).map(S=>{const _=S.message,T=typeof _?.method=="string"?_.method:_?.result!==void 0?"result":_?.error!==void 0?"error":"unknown";return{id:`${S.timestamp}-${Math.random().toString(36).slice(2)}`,serverId:S.serverId,direction:S.direction.toUpperCase(),method:T,timestamp:S.timestamp,payload:S.message}}).reverse();a(x),t?.(x.length);const w=_N(S=>{if(e&&e.length>0&&!e.includes(S.serverId))return;const _=S.message,T=typeof _?.method=="string"?_.method:_?.result!==void 0?"result":_?.error!==void 0?"error":"unknown",k={id:`${S.timestamp}-${Math.random().toString(36).slice(2)}`,serverId:S.serverId,direction:S.direction.toUpperCase(),method:T,timestamp:S.timestamp,payload:S.message};console.log("[RPC Logger] New RPC log:",{method:T,direction:S.direction,serverId:S.serverId}),a(R=>{const A=[k,...R].slice(0,1e3);return t?.(A.length),A})});return()=>{w(),console.log("[RPC Logger] Unsubscribed from RPC logs")}},[h,t]);const g=y.useMemo(()=>{let b=r;if(e&&e.length>0){const E=new Set(e);b=b.filter(x=>E.has(x.serverId))}if(u.trim()){const E=u.toLowerCase();b=b.filter(x=>x.serverId.toLowerCase().includes(E)||x.method.toLowerCase().includes(E)||x.direction.toLowerCase().includes(E)||JSON.stringify(x.payload).toLowerCase().includes(E))}return b=[...b].sort((E,x)=>new Date(x.timestamp).getTime()-new Date(E.timestamp).getTime()),b},[r,u,e]);return d.jsx("div",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:d.jsx("div",{ref:o,className:"flex-1 min-h-0 overflow-y-auto",children:g.length===0?d.jsxs("div",{className:"text-center py-8",children:[d.jsx("div",{className:"text-xs text-muted-foreground",children:"No messages yet"}),d.jsx("div",{className:"text-[10px] text-muted-foreground mt-1",children:"JSON-RPC messages will appear here"})]}):g.map(b=>{const E=i.has(b.id);return d.jsxs("div",{className:"group hover:bg-muted/50 transition-all duration-200 overflow-hidden",children:[d.jsxs("div",{className:"px-3 py-2 flex items-center gap-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>f(b.id),children:[d.jsx("div",{className:"flex-shrink-0",children:E?d.jsx(hs,{className:"h-3 w-3 text-muted-foreground transition-transform"}):d.jsx(zH,{className:"h-3 w-3 text-muted-foreground transition-transform"})}),d.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[d.jsx("span",{className:"text-muted-foreground font-mono text-xs",children:new Date(b.timestamp).toLocaleTimeString()}),d.jsx("span",{className:`flex items-center justify-center px-1 py-0.5 rounded ${b.direction==="RECEIVE"?"bg-blue-500/10 text-blue-600 dark:text-blue-400":"bg-green-500/10 text-green-600 dark:text-green-400"}`,title:b.direction==="RECEIVE"?"Incoming":"Outgoing",children:b.direction==="RECEIVE"?d.jsx(Zce,{className:"h-3 w-3"}):d.jsx(Xce,{className:"h-3 w-3"})}),d.jsx("span",{className:"text-xs font-mono text-foreground truncate",children:b.method})]})]}),E&&d.jsx("div",{className:"border-t bg-muted/20",children:d.jsx("div",{className:"p-3",children:d.jsx("div",{className:"max-h-[40vh] overflow-auto rounded-sm bg-background/60 p-2",children:d.jsx(yr,{data:b.payload})})})})]},b.id)})})})}function jW({activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabTitle:r,secondaryTabTitle:a,primaryCount:o,secondaryCount:i,secondaryIcon:l,primaryIcon:u,searchPlaceholder:f="Search...",onSearchExpand:m,onSearchChange:h,onSearchBlur:g,onTabSwitch:b,searchInputRef:E,primaryTabName:x}){const w=e===x;return d.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[d.jsx("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:t?d.jsx(Hn,{ref:E,placeholder:f,value:n,onChange:S=>h(S.target.value),onBlur:g,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:w?r:a}),w&&d.jsxs(d.Fragment,{children:[d.jsx(Pr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:o}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:m,className:"h-8 w-8 p-0",children:d.jsx(sf,{className:"h-4 w-4"})})}),d.jsxs(Yt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(xh,{children:"F"})]})]})]})]})}),d.jsxs(Me,{variant:"ghost",size:"sm",onClick:b,className:"gap-2 flex-shrink-0",children:[w?d.jsx(l,{}):d.jsx(u,{}),d.jsx("span",{className:"hidden sm:inline",children:w?a:r}),w&&i>0&&d.jsx(Pr,{className:"bg-purple-500/20 text-purple-600 dark:text-purple-400 border-transparent",variant:"outline",children:i})]})]})}function kF({prompts:e,selectedPrompt:t,onPromptSelect:n,focusedIndex:r}){return e.length===0?d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(pm,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No prompts available"})]}):d.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((a,o)=>d.jsx(El,{id:`prompt-${a.name}`,isSelected:t?.name===a.name,isFocused:r===o,icon:d.jsx(pm,{className:"h-4 w-4"}),title:a.name,description:a.description,metadata:a.arguments&&a.arguments.length>0&&d.jsxs(Pr,{variant:"outline",className:"text-xs border-gray-300 dark:border-zinc-600 text-gray-600 dark:text-gray-400",children:[a.arguments.length," args"]}),onClick:()=>n(a)},a.name))})}function AF({activeTab:e,isSearchExpanded:t,searchQuery:n,filteredPromptsCount:r,savedPromptsCount:a,onSearchExpand:o,onSearchChange:i,onSearchBlur:l,onTabSwitch:u,searchInputRef:f}){return d.jsx(jW,{activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabName:"prompts",secondaryTabName:"saved",primaryTabTitle:"Prompts",secondaryTabTitle:"History",primaryCount:r,secondaryCount:a,primaryIcon:pm,secondaryIcon:um,searchPlaceholder:"Search prompts...",onSearchExpand:o,onSearchChange:i,onSearchBlur:l,onTabSwitch:u,searchInputRef:f})}function IF({savedPrompts:e,selectedPrompt:t,onLoadPrompt:n,onDeletePrompt:r,focusedIndex:a}){return e.length===0?d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(um,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No history"}),d.jsx("p",{className:"text-sm text-gray-400 dark:text-gray-500 mt-1",children:"Prompts you execute will appear here"})]}):d.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((o,i)=>d.jsx(El,{id:`saved-prompt-${o.id}`,isSelected:t?.id===o.id,isFocused:a===i,icon:d.jsx(um,{className:"h-4 w-4"}),title:o.name,description:`${o.promptName} - ${new Date(o.savedAt).toLocaleString()}`,onClick:()=>n(o)},o.id))})}function H_e({selectedPrompt:e,promptArgs:t,onArgChange:n}){const r=e?.arguments||[];if(!(r.length>0))return d.jsx("div",{className:"flex items-center justify-center h-32 text-gray-500 dark:text-gray-400 text-sm",children:"No arguments required"});const o=i=>{const l=i.name,u=t[l],f=typeof u=="string"?u:JSON.stringify(u);return i.type==="boolean"?d.jsxs("div",{className:"space-y-2",children:[d.jsxs(wn,{htmlFor:l,className:"text-sm font-medium",children:[l,i.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsxs("div",{className:"flex items-center space-x-2",children:[d.jsx("input",{id:l,type:"checkbox",checked:!!u,onChange:m=>n(l,m.target.checked),className:"rounded","aria-label":`Toggle ${l}`}),d.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:i.description})]})]},l):i.type==="number"?d.jsxs("div",{className:"space-y-2",children:[d.jsxs(wn,{htmlFor:l,className:"text-sm font-medium",children:[l,i.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsx(Hn,{id:l,type:"number",value:Number(u)||0,onChange:m=>n(l,Number(m.target.value)),placeholder:i.description||`Enter ${l}`}),i.description&&d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:i.description})]},l):i.type==="array"||i.type==="object"?d.jsxs("div",{className:"space-y-2",children:[d.jsxs(wn,{htmlFor:l,className:"text-sm font-medium",children:[l,i.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsx(bc,{id:l,value:f,onChange:m=>{try{const h=JSON.parse(m.target.value);n(l,h)}catch{n(l,m.target.value)}},placeholder:i.description||`Enter ${l} as JSON`,className:"font-mono text-sm min-h-[100px]"}),i.description&&d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:i.description})]},l):d.jsxs("div",{className:"space-y-2",children:[d.jsxs(wn,{htmlFor:l,className:"text-sm font-medium",children:[l,i.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsx(Hn,{id:l,value:f,onChange:m=>n(l,m.target.value),placeholder:i.description||`Enter ${l}`}),i.description&&d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:i.description})]},l)};return d.jsx("div",{className:"space-y-4",children:r.map(i=>o(i))})}function OF({selectedPrompt:e,promptArgs:t,isExecuting:n,isConnected:r,onArgChange:a,onExecute:o,onSave:i}){return y.useEffect(()=>{const l=u=>{(u.metaKey||u.ctrlKey)&&u.key==="Enter"&&e&&!n&&r&&(u.preventDefault(),o())};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[e,n,r,o]),e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsx("div",{className:"flex-shrink-0 p-3 sm:p-6 pt-3 pb-4 pr-3",children:d.jsxs("div",{children:[d.jsxs("div",{className:"flex flex-row items-center justify-between mb-0 gap-2",children:[d.jsx("h3",{className:"text-base sm:text-lg font-semibold",children:e.name}),d.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[d.jsx(Me,{onClick:o,disabled:n||!r,size:"sm",className:"lg:size-default pr-1! gap-0",children:n?d.jsxs(d.Fragment,{children:[d.jsx(gs,{className:"mr-2"}),d.jsx("span",{className:"hidden sm:inline",children:"Executing..."})]}):d.jsxs(d.Fragment,{children:[d.jsx(GH,{className:"h-4 w-4 sm:mr-2"}),d.jsx("span",{className:"hidden sm:inline",children:"Execute"}),d.jsx("span",{className:"hidden sm:inline text-[12px] border text-zinc-300 p-1 rounded-full border-zinc-300 dark:text-zinc-600 dark:border-zinc-500 ml-2",children:"⌘↵"})]})}),d.jsxs(Me,{variant:"outline",onClick:i,disabled:n,size:"sm",className:"lg:size-default gap-2",children:[d.jsx(XN,{className:"h-4 w-4"}),d.jsx("span",{className:"hidden sm:inline",children:"Save"})]})]})]}),e.description&&d.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 leading-relaxed mt-2",children:e.description})]})}),d.jsx("div",{className:"flex-1 overflow-y-auto px-3 sm:px-6 pb-4 pr-3",children:d.jsx(H_e,{selectedPrompt:e,promptArgs:t,onArgChange:a})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"Select a prompt to get started"}),d.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Choose a prompt from the list to view its details and execute it"})]})}function V_e(e){switch(e){case"system":return"default";case"user":return"outline";case"assistant":return"secondary";default:return"outline"}}function G_e(e){return e.charAt(0).toUpperCase()+e.slice(1)}function W_e(e){return typeof e=="string"?e:e.text?e.text:e.type==="resource"&&e.resource?.text?e.resource.text:e.type==="image"?`[Image: ${e.mimeType||"unknown type"}]`:JSON.stringify(e,null,2)}function K_e({message:e,index:t}){const[n,r]=y.useState(!1),a=async()=>{const i=W_e(e.content);await navigator.clipboard.writeText(i),r(!0),setTimeout(()=>r(!1),2e3)},o=()=>{const i=e.content;return typeof i=="string"?d.jsx(vy,{content:i}):i.type==="text"&&i.text?d.jsx(vy,{content:i.text}):i.type==="image"?d.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[d.jsxs("span",{className:"font-mono bg-muted px-2 py-1 rounded",children:["Image: ",i.mimeType||"unknown type"]}),i.data&&d.jsx("img",{src:`data:${i.mimeType};base64,${i.data}`,alt:"Prompt image",className:"max-w-full max-h-[300px] object-contain rounded-lg border border-border mt-2"})]}):i.type==="resource"&&i.resource?d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[d.jsx("span",{className:"text-muted-foreground font-medium",children:"Resource:"}),d.jsx("code",{className:"bg-muted px-2 py-0.5 rounded text-xs font-mono",children:i.resource.uri})]}),i.resource.text&&d.jsx("div",{className:"mt-2",children:d.jsx(vy,{content:i.resource.text})})]}):d.jsx("pre",{className:"bg-muted p-3 rounded-lg text-sm overflow-x-auto",children:d.jsx("code",{children:JSON.stringify(i,null,2)})})};return d.jsxs("div",{className:"border border-border rounded-lg overflow-hidden bg-white dark:bg-zinc-900",children:[d.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-muted/30 border-b border-border",children:[d.jsx(Pr,{variant:V_e(e.role),children:G_e(e.role)}),d.jsx(Me,{variant:"ghost",size:"sm",onClick:a,className:"h-6 px-2",title:"Copy message content",children:n?d.jsx(Or,{className:"h-3.5 w-3.5"}):d.jsx(wr,{className:"h-3.5 w-3.5"})})]}),d.jsx("div",{className:"px-4 py-3",children:o()})]})}function Y_e(e){const n=Date.now()-e,r=Math.floor(n/1e3),a=Math.floor(r/60),o=Math.floor(a/60),i=Math.floor(o/24);return r<10?"now":r<60?`${r}s ago`:a<60?`${a}m ago`:o<24?`${o}h ago`:`${i}d ago`}function Z_e(e){return"isError"in e&&!e.isError?null:"error"in e&&e.error?e.error:"isError"in e&&e.isError?"An error occurred":null}function DF({results:e,copiedResult:t,previewMode:n=!0,onCopy:r,onDelete:a,onFullscreen:o,onTogglePreview:i,onMaximize:l,isMaximized:u=!1}){const[f,m]=y.useState(0),[h,g]=y.useState(""),[b,E]=y.useState(!0),x=e[0],w=x?e.filter(R=>R.promptName===x.promptName):[],S=w[f]||w[0],_=e.findIndex(R=>R===S);if(y.useEffect(()=>{w.length>0&&f>=w.length&&m(0)},[w.length,f]),y.useEffect(()=>{const R=()=>{S&&g(Y_e(S.timestamp))};R();const A=setInterval(R,1e3);return()=>clearInterval(A)},[S]),e.length===0)return d.jsx("div",{className:"flex flex-col h-full bg-white dark:bg-black border-t dark:border-zinc-700",children:d.jsx("div",{className:"flex-1 overflow-y-auto h-full",children:d.jsx("div",{className:"flex items-center justify-center h-full",children:d.jsx("div",{className:"text-center",children:d.jsx(of,{vertical:!0,noBorder:!0,message:"No Results yet"})})})})});const T=S.error||Z_e(S.result),k="messages"in S.result&&Array.isArray(S.result.messages);return d.jsx("div",{className:"flex flex-col h-full bg-white dark:bg-black border-t dark:border-zinc-700",children:d.jsx("div",{className:"flex-1 overflow-y-auto h-full",children:d.jsxs("div",{className:"space-y-0 flex-1 h-full flex flex-col",children:[d.jsxs("div",{className:"flex items-center gap-2 px-4 pt-2 border-b border-gray-200 dark:border-zinc-600 pb-2",children:[d.jsx("h3",{className:"text-sm font-medium hidden sm:block",children:"Response"}),S.duration!==void 0&&d.jsxs("div",{className:"hidden sm:flex items-center gap-1",children:[d.jsx(hm,{className:"h-3 w-3 text-gray-400"}),d.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[S.duration,"ms"]})]}),k&&d.jsx("div",{className:"flex items-center gap-4 sm:ml-4",children:d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>E(!0),className:`text-xs font-medium ${b?"text-black dark:text-white":"text-zinc-500 dark:text-zinc-400"}`,children:"Formatted"}),d.jsx("span",{className:"text-xs text-zinc-400",children:"|"}),d.jsx("button",{onClick:()=>E(!1),className:`text-xs font-medium ${b?"text-zinc-500 dark:text-zinc-400":"text-black dark:text-white"}`,children:"Raw"})]})}),d.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[w.length>1&&d.jsxs("div",{className:"flex items-center gap-2 mr-2",children:[d.jsx(dm,{className:"h-3 w-3 text-gray-400"}),d.jsxs(Zs,{value:f.toString(),onValueChange:R=>m(parseInt(R)),children:[d.jsx(Xs,{className:"h-7 w-[120px] text-xs",children:d.jsx(qs,{})}),d.jsx(Js,{children:w.map((R,A)=>d.jsx(fa,{value:A.toString(),children:A===0?"Latest":`${A+1} call ago`},A))})]})]}),d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 mr-2",children:h}),d.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>r(_,S.result),className:"h-7 w-7 p-0",title:"Copy result",children:t===_?d.jsx(Or,{className:"h-4 w-4"}):d.jsx(wr,{className:"h-4 w-4"})}),a&&d.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>a(_),className:"h-7 w-7 p-0",title:"Delete result",children:d.jsx(ni,{className:"h-4 w-4"})}),o&&d.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>o(_),className:"h-7 w-7 p-0 sm:hidden",title:"Fullscreen",children:d.jsx(fm,{className:"h-4 w-4"})}),l&&d.jsx(Me,{variant:"ghost",size:"sm",onClick:l,className:"h-7 w-7 p-0 hidden sm:flex",title:u?"Restore":"Maximize",children:u?d.jsx(VH,{className:"h-4 w-4"}):d.jsx(fm,{className:"h-4 w-4"})})]})]}),d.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:T?d.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded p-3",children:[d.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Error:"}),d.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:T})]}):b&&k?d.jsx("div",{className:"space-y-3",children:S.result.messages.map((R,A)=>d.jsx(K_e,{message:R,index:A},A))}):d.jsx(yr,{data:S.result,filename:`prompt-result-${S.promptName}-${Date.now()}.json`})})]})})})}const LF="mcp-inspector-saved-prompts";function PW({ref:e,prompts:t,callPrompt:n,serverId:r,isConnected:a}){const[o,i]=y.useState(null),[l,u]=y.useState(null),{selectedPromptName:f,setSelectedPromptName:m}=kc(),[h,g]=y.useState({}),[b,E]=y.useState([]),[x,w]=y.useState(!1),[S,_]=y.useState(null),[T,k]=y.useState(""),[R,A]=y.useState("prompts"),[C,O]=y.useState([]),[M,L]=y.useState(!1),[j,B]=y.useState(""),[K,Z]=y.useState(!1),[te,V]=y.useState(-1),Y=y.useRef(null),[F,ae]=y.useState(!1),[ee,P]=y.useState("list"),[H,U]=y.useState(0),[D,$]=y.useState(!0),[G,W]=y.useState(!1),re=y.useRef(null),pe=y.useRef(null),me=y.useRef(null),ne=y.useRef(null);y.useEffect(()=>{const Ce=()=>{ae(window.innerWidth<1024)};return Ce(),window.addEventListener("resize",Ce),()=>window.removeEventListener("resize",Ce)},[]),y.useEffect(()=>{P(o?"detail":"list")},[o]),y.useEffect(()=>{F&&b.length>0&&!x&&P("response")},[b,x,F]),y.useImperativeHandle(e,()=>({focusSearch:()=>{Z(!0),setTimeout(()=>{Y.current&&Y.current.focus()},0)},blurSearch:()=>{k(""),Z(!1),Y.current&&Y.current.blur()}})),y.useEffect(()=>{try{const Ce=localStorage.getItem(LF);if(Ce){const He=JSON.parse(Ce);O(He)}}catch(Ce){console.error("[PromptsTab] Failed to load saved prompts:",Ce)}},[]);const J=y.useCallback(Ce=>{try{localStorage.setItem(LF,JSON.stringify(Ce))}catch(He){console.error("[PromptsTab] Failed to save prompts:",He)}},[]);y.useEffect(()=>{K&&Y.current&&Y.current.focus()},[K]);const X=y.useCallback(()=>{T.trim()||Z(!1)},[T]),se=y.useMemo(()=>{if(!T.trim())return t;const Ce=T.toLowerCase();return t.filter(He=>He.name.toLowerCase().includes(Ce)||He.description?.toLowerCase().includes(Ce))},[t,T]),he=y.useCallback(Ce=>{i(Ce);const He={};Ce.arguments&&Ce.arguments.forEach(st=>{He[st.name]=""}),g(He)},[]),Te=y.useCallback(Ce=>{const He=t.find(st=>st.name===Ce.promptName);He&&(i(He),g(Ce.args),u(Ce))},[t]);y.useEffect(()=>{V(-1)},[T,R]),y.useEffect(()=>{const Ce=He=>{const st=He.target;if(st.tagName==="INPUT"||st.tagName==="TEXTAREA"||st.contentEditable==="true"||He.metaKey||He.ctrlKey||He.altKey)return;const it=R==="prompts"?se:C;if(He.key==="ArrowDown")He.preventDefault(),V(kt=>{const Nn=kt+1;return Nn>=it.length?0:Nn});else if(He.key==="ArrowUp")He.preventDefault(),V(kt=>{const Nn=kt-1;return Nn<0?it.length-1:Nn});else if(He.key==="Enter"&&te>=0)if(He.preventDefault(),R==="prompts"){const kt=se[te];kt&&he(kt)}else{const kt=C[te];kt&&Te(kt)}};return document.addEventListener("keydown",Ce),()=>document.removeEventListener("keydown",Ce)},[te,se,C,R,he,Te]),y.useEffect(()=>{if(te>=0){const Ce=R==="prompts"?`prompt-${se[te]?.name}`:`saved-prompt-${C[te]?.id}`,He=document.getElementById(Ce);He&&He.scrollIntoView({behavior:"smooth",block:"nearest"})}},[te,se,C,R]),y.useEffect(()=>{if(console.warn("[PromptsTab] Auto-selection effect triggered:",{selectedPromptName:f,promptsCount:t.length,currentSelectedPrompt:o?.name}),f&&t.length>0){const Ce=t.find(He=>He.name===f);if(console.warn("[PromptsTab] Prompt lookup result:",{selectedPromptName:f,promptFound:!!Ce,promptName:Ce?.name,shouldSelect:Ce&&o?.name!==Ce.name}),Ce&&o?.name!==Ce.name){console.warn("[PromptsTab] Selecting prompt:",Ce.name),m(null);const He=setTimeout(()=>{he(Ce);const st=document.getElementById(`prompt-${Ce.name}`);st&&(console.warn("[PromptsTab] Scrolling to prompt element"),st.scrollIntoView({behavior:"smooth",block:"nearest"}))},100);return()=>clearTimeout(He)}}},[f,t,o,he,m]);const Be=y.useCallback((Ce,He)=>{g(st=>({...st,[Ce]:He}))},[]),$e=y.useCallback(async()=>{if(!o||x)return;w(!0);const Ce=Date.now();try{const He=await n(o.name,h),st=Date.now()-Ce;ra.getInstance().capture(new bU({promptName:o.name,serverId:r,success:!0})).catch(()=>{}),E(it=>[{promptName:o.name,args:h,result:He,timestamp:Ce,duration:st},...it])}catch(He){ra.getInstance().capture(new bU({promptName:o.name,serverId:r,success:!1,error:He instanceof Error?He.message:"Unknown error"})).catch(()=>{});const Je={promptName:o.name,args:h,result:null,error:He instanceof Error?He.message:String(He),timestamp:Ce,duration:Date.now()-Ce};E(it=>[...it,{...Je,result:{messages:[]}}])}finally{w(!1)}},[o,h,x,n,r]),Ge=y.useCallback(async(Ce,He)=>{try{await navigator.clipboard.writeText(JSON.stringify(He,null,2)),_(Ce),setTimeout(()=>_(null),2e3)}catch(st){console.error("[PromptsTab] Failed to copy result:",st)}},[]),dt=y.useCallback(Ce=>{E(He=>He.filter((st,Je)=>Je!==Ce))},[]),Ve=y.useCallback(Ce=>{if(F)P("response");else{const He=b[Ce];if(He){const st=window.open("","_blank","width=800,height=600");if(st){const Je=He.result;st.document.write(`
1753
+ `);T=A.pop()||"";for(const C of A)if(C.trim()&&C.startsWith("data: "))try{const O=JSON.parse(C.slice(6));if(console.log("[Client received event]",O.type,O.toolName||O.content?.slice?.(0,30)),O.type==="message")console.log("[Message started]",O.id);else if(O.type==="text"){x+=O.content;const M=w[w.length-1];M&&M.type==="text"?M.text=x:w.push({type:"text",text:x}),console.log("[Parts after text]",w.length,"parts, text length:",x.length),o(L=>L.map(j=>j.id===E?{...j,parts:[...w]}:j))}else if(O.type==="tool-call")x&&(x=""),w.push({type:"tool-invocation",toolInvocation:{toolName:O.toolName,args:O.args,state:"pending"}}),console.log("[Parts after tool-call]",w.length,"parts, tool:",O.toolName),o(M=>M.map(L=>L.id===E?{...L,parts:[...w]}:L));else if(O.type==="tool-result"){const M=w.find(L=>L.type==="tool-invocation"&&L.toolInvocation?.toolName===O.toolName&&!L.toolInvocation?.result);M&&M.toolInvocation?(M.toolInvocation.result=O.result,M.toolInvocation.state="result",console.log("[Parts after tool-result]",w.length,"parts, updated:",O.toolName),o(L=>L.map(j=>j.id===E?{...j,parts:[...w]}:j))):console.warn("[tool-result] Could not find matching tool part for",O.toolName)}else if(O.type==="done")console.log("[Done] Final parts:",w.length),o(M=>M.map(L=>L.id===E?{...L,parts:[...w],content:""}:L));else if(O.type==="error")throw new Error(O.message||"Streaming error")}catch(O){console.error("Failed to parse streaming event:",O,C)}}}catch(g){let b="Unknown error occurred";if(g instanceof Error){b=g.message;const x=g;x.status&&(b=`HTTP ${x.status}: ${b}`),(x.code===401||b.includes("401")||b.includes("Unauthorized"))&&(b="Authentication failed (401). Check your Authorization header in the connection settings.")}const E={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${b}`,timestamp:Date.now()};o(x=>[...x,E])}finally{l(!1)}},[t,r,e,a,n]),f=y.useCallback(()=>{o([])},[]);return{messages:a,isLoading:i,sendMessage:u,clearMessages:f}}function c_e({connection:e,llmConfig:t,isConnected:n,readResource:r}){const[a,o]=y.useState([]),[i,l]=y.useState(!1),u=y.useRef(null),f=y.useRef(null),m=y.useRef(null),h=y.useCallback(async b=>{if(!b.trim()||!t||!n)return;const E={id:`user-${Date.now()}`,role:"user",content:b.trim(),timestamp:Date.now()};o(S=>[...S,E]),l(!0),u.current=new AbortController;const x=Date.now();let w=0;try{const S=`assistant-${Date.now()}`;let _="";const T=[];if(o(k=>[...k,{id:S,role:"assistant",content:"",timestamp:Date.now(),parts:[]}]),!m.current||m.current.provider!==t.provider||m.current.model!==t.model||m.current.apiKey!==t.apiKey){let k;if(t.provider==="openai"){const{ChatOpenAI:R}=await Ua(async()=>{const{ChatOpenAI:A}=await import("./index-CR746V6H.js");return{ChatOpenAI:A}},__vite__mapDeps([0,1,2,3,4,5]));k=new R({model:t.model,apiKey:t.apiKey})}else if(t.provider==="anthropic"){const{ChatAnthropic:R}=await Ua(async()=>{const{ChatAnthropic:A}=await import("./index-C6J4X9FC.js");return{ChatAnthropic:A}},__vite__mapDeps([6,2,1,5]));k=new R({model:t.model,apiKey:t.apiKey})}else if(t.provider==="google"){const{ChatGoogleGenerativeAI:R}=await Ua(async()=>{const{ChatGoogleGenerativeAI:A}=await import("./index-BVVKUeFG.js");return{ChatGoogleGenerativeAI:A}},__vite__mapDeps([7,2,1,4]));k=new R({model:t.model,apiKey:t.apiKey})}else throw new Error(`Unsupported LLM provider: ${t.provider}`);m.current={instance:k,provider:t.provider,model:t.model,apiKey:t.apiKey}}if(!f.current||f.current.llm!==m.current.instance){const{MCPAgent:k}=await Ua(async()=>{const{MCPAgent:R}=await import("./browser-jWg_baZz.js");return{MCPAgent:R}},__vite__mapDeps([8,5,1,2,4,3]));f.current=new k({llm:m.current.instance,client:e.client,memoryEnabled:!0,systemPrompt:"You are a helpful assistant with access to MCP tools, prompts, and resources. Help users interact with the MCP server."}),await f.current.initialize()}else console.log("[useChatMessagesClientSide] Reusing existing agent. History length:",f.current.conversationHistory?.length);for await(const k of f.current.streamEvents(b,10,!1,void 0)){if(u.current?.signal.aborted)break;if(k.event==="on_chat_model_stream"&&k.data?.chunk?.text){const R=k.data.chunk.text;if(typeof R=="string"&&R.length>0){_+=R;const A=T[T.length-1];A&&A.type==="text"?A.text=_:T.push({type:"text",text:_}),o(C=>C.map(O=>O.id===S?{...O,parts:[...T]}:O))}}else if(k.event==="on_tool_start"){_&&(_="");let R={};k.data?.input?R=k.data.input:k.data?.tool_input?R=k.data.tool_input:k.data&&(R=k.data),console.log("[useChatMessagesClientSide] on_tool_start:",{toolName:k.name,eventData:k.data,extractedArgs:R}),w++,T.push({type:"tool-invocation",toolInvocation:{toolName:k.name||"unknown",args:R,state:"pending"}}),o(A=>A.map(C=>C.id===S?{...C,parts:[...T]}:C))}else if(k.event==="on_tool_end"){const R=T.find(A=>A.type==="tool-invocation"&&A.toolInvocation?.toolName===k.name&&!A.toolInvocation?.result);if(console.log("[useChatMessagesClientSide] on_tool_end event:",{toolName:k.name,hasToolPart:!!R,output:k.data?.output}),R&&R.toolInvocation){let A=k.data?.output;if(A?.kwargs?.content&&typeof A.kwargs.content=="string")try{A=JSON.parse(A.kwargs.content)}catch(O){console.warn("[useChatMessagesClientSide] Failed to parse kwargs.content:",O),A=A.kwargs.content}else if(A?.content&&typeof A.content=="string")try{A=JSON.parse(A.content)}catch{A=A.content}R.toolInvocation.result=A,R.toolInvocation.state="result";const C=A?._meta?.["openai/outputTemplate"];if(console.log("[useChatMessagesClientSide] Tool result:",{toolName:k.name,hasMeta:!!A?._meta,hasStructuredContent:!!A?.structuredContent,appsSdkUri:C}),C&&typeof C=="string"&&r){console.log("[useChatMessagesClientSide] Detected Apps SDK component, fetching resource:",C);try{const O=await r(C);console.log("[useChatMessagesClientSide] Resource fetched:",O);const M=A?.structuredContent||null;if(O?.contents&&Array.isArray(O.contents)){const L=O.contents.map(B=>({type:"resource",resource:B}));console.log("[useChatMessagesClientSide] Created MCP resources:",L);const j={...A,content:[...A.content||[],...L],structuredContent:M};R.toolInvocation.result=j,console.log("[useChatMessagesClientSide] Updated result with resources")}else console.warn("[useChatMessagesClientSide] No contents in resourceData:",O)}catch(O){console.error("Failed to fetch Apps SDK resource:",O)}}o(O=>O.map(M=>M.id===S?{...M,parts:[...T]}:M))}}}o(k=>k.map(R=>R.id===S?{...R,parts:[...T],content:""}:R)),t&&ra.getInstance().capture(new yU({serverId:e.url,provider:t.provider,model:t.model,messageCount:a.length+1,toolCallsCount:w,success:!0,executionMode:"client-side",duration:Date.now()-x})).catch(()=>{})}catch(S){console.error("Client-side agent error:",S);let _="Unknown error occurred";if(S instanceof Error){_=S.message;const k=S;k.status&&(_=`HTTP ${k.status}: ${_}`),(k.code===401||_.includes("401")||_.includes("Unauthorized"))&&(_="Authentication failed (401). Check your Authorization header in the connection settings.")}t&&ra.getInstance().capture(new yU({serverId:e.url,provider:t.provider,model:t.model,messageCount:a.length+1,toolCallsCount:w,success:!1,executionMode:"client-side",duration:Date.now()-x,error:_})).catch(()=>{});const T={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${_}`,timestamp:Date.now()};o(k=>[...k,T])}finally{l(!1),u.current=null}},[e,t,n,a,r]),g=y.useCallback(()=>{o([]),f.current&&f.current.clearConversationHistory()},[]);return{messages:a,isLoading:i,sendMessage:h,clearMessages:g}}const wF={openai:"gpt-4o",anthropic:"claude-haiku-4-5-20251001",google:"gemini-2.5-flash"};function mW({mcpServerUrl:e}){const[t,n]=y.useState(null),[r,a]=y.useState(null),[o,i]=y.useState(!1),[l,u]=y.useState("openai"),[f,m]=y.useState(""),[h,g]=y.useState(wF.openai),b=y.useCallback(()=>{const M=localStorage.getItem("mcp-inspector-api-keys");if(M)try{return JSON.parse(M)}catch(L){return console.error("Failed to load API keys:",L),{}}return{}},[]),E=y.useCallback(M=>{localStorage.setItem("mcp-inspector-api-keys",JSON.stringify(M))},[]),[x,w]=y.useState("none"),[S,_]=y.useState(""),[T,k]=y.useState(""),[R,A]=y.useState("");y.useEffect(()=>{const M=localStorage.getItem("mcp-inspector-llm-config"),L=b();if(M)try{const j=JSON.parse(M);n(j),u(j.provider),m(L[j.provider]||j.apiKey||""),g(j.model)}catch(j){console.error("Failed to load LLM config:",j)}},[b]),y.useEffect(()=>{const M=localStorage.getItem("mcp-inspector-auth-config");if(M)try{const L=JSON.parse(M);a(L),w(L.type),L.username&&_(L.username),L.password&&k(L.password),L.token&&A(L.token)}catch(L){console.error("Failed to load auth config:",L)}else try{const L="mcp:auth",j=pW(e),B=`${L}_${j}_tokens`;localStorage.getItem(B)&&(a({type:"oauth"}),w("oauth"))}catch(L){console.error("Failed to check for OAuth tokens:",L)}},[e]),y.useEffect(()=>{g(wF[l]);const M=b();m(M[l]||"")},[l,b]);const C=y.useCallback(()=>{if(!f.trim())return;const M=b();M[l]=f,E(M);const L={provider:l,apiKey:f,model:h},j={type:x,...x==="basic"&&{username:S.trim(),password:T.trim()},...x==="bearer"&&{token:R.trim()}};n(L),a(j),localStorage.setItem("mcp-inspector-llm-config",JSON.stringify(L)),localStorage.setItem("mcp-inspector-auth-config",JSON.stringify(j)),i(!1)},[l,f,h,x,S,T,R,b,E]),O=y.useCallback(()=>{n(null),a(null);const M=b();delete M[l],E(M),m(""),_(""),k(""),A(""),w("none"),localStorage.removeItem("mcp-inspector-llm-config"),localStorage.removeItem("mcp-inspector-auth-config")},[l,b,E]);return{llmConfig:t,authConfig:r,configDialogOpen:o,setConfigDialogOpen:i,tempProvider:l,setTempProvider:u,tempApiKey:f,setTempApiKey:m,tempModel:h,setTempModel:g,tempAuthType:x,saveLLMConfig:C,clearConfig:O}}function u_e({connection:e,isConnected:t,useClientSide:n=!0,readResource:r}){const[a,o]=y.useState(""),i=y.useRef(null),{llmConfig:l,authConfig:u,configDialogOpen:f,setConfigDialogOpen:m,tempProvider:h,setTempProvider:g,tempApiKey:b,setTempApiKey:E,tempModel:x,setTempModel:w,saveLLMConfig:S,clearConfig:_}=mW({mcpServerUrl:e.url}),T={connection:e,llmConfig:l,isConnected:t,readResource:r},k=l_e({mcpServerUrl:e.url,llmConfig:l,authConfig:u,isConnected:t}),R=c_e(T),{messages:A,isLoading:C,sendMessage:O,clearMessages:M}=n?R:k;NG({onNewChat:M}),y.useEffect(()=>{l&&A.length===0&&i.current&&i.current.focus()},[l,A.length]),y.useEffect(()=>{!C&&A.length>0&&i.current&&i.current.focus()},[C,A.length]);const L=y.useCallback(()=>{a.trim()&&(O(a),o(""))},[a,O]),j=y.useCallback(K=>{K.key==="Enter"&&!K.shiftKey&&(K.preventDefault(),L())},[L]),B=y.useCallback(()=>{_(),M()},[_,M]);return l&&A.length===0?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsx("div",{className:"absolute top-4 right-4 z-10",children:d.jsx(gT,{open:f,onOpenChange:m,tempProvider:h,tempModel:x,tempApiKey:b,onProviderChange:g,onModelChange:w,onApiKeyChange:E,onSave:S,onClear:B,showClearButton:!0,buttonLabel:"Change API Key"})}),d.jsx($xe,{mcpServerUrl:e.url,inputValue:a,isConnected:t,isLoading:C,textareaRef:i,llmConfig:l,onInputChange:o,onKeyDown:j,onSubmit:K=>{K.preventDefault(),L()},onConfigDialogOpenChange:m})]}):d.jsxs("div",{className:"flex flex-col h-full relative",children:[d.jsx(Mxe,{llmConfig:l,hasMessages:A.length>0,configDialogOpen:f,onConfigDialogOpenChange:m,onClearChat:M,tempProvider:h,tempModel:x,tempApiKey:b,onProviderChange:g,onModelChange:w,onApiKeyChange:E,onSaveConfig:S,onClearConfig:B}),d.jsx("div",{className:"flex-1 overflow-y-auto p-2 sm:p-4 pt-[80px] sm:pt-[100px]",children:l?d.jsx(i_e,{messages:A,isLoading:C,serverId:e.url,readResource:r,tools:e.tools}):d.jsx(Uxe,{onConfigureClick:()=>m(!0)})}),l&&d.jsx(jxe,{inputValue:a,isConnected:t,isLoading:C,textareaRef:i,onInputChange:o,onKeyDown:j,onSendMessage:L})]})}const Uw=y.createContext(null);Uw.displayName="PanelGroupContext";const br={group:"data-panel-group",groupDirection:"data-panel-group-direction",groupId:"data-panel-group-id",panel:"data-panel",panelCollapsible:"data-panel-collapsible",panelId:"data-panel-id",panelSize:"data-panel-size",resizeHandle:"data-resize-handle",resizeHandleActive:"data-resize-handle-active",resizeHandleEnabled:"data-panel-resize-handle-enabled",resizeHandleId:"data-panel-resize-handle-id",resizeHandleState:"data-resize-handle-state"},VO=10,ic=y.useLayoutEffect,xF=Ec.useId,d_e=typeof xF=="function"?xF:()=>null;let f_e=0;function GO(e=null){const t=d_e(),n=y.useRef(e||t||null);return n.current===null&&(n.current=""+f_e++),e??n.current}function hW({children:e,className:t="",collapsedSize:n,collapsible:r,defaultSize:a,forwardedRef:o,id:i,maxSize:l,minSize:u,onCollapse:f,onExpand:m,onResize:h,order:g,style:b,tagName:E="div",...x}){const w=y.useContext(Uw);if(w===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:S,expandPanel:_,getPanelSize:T,getPanelStyle:k,groupId:R,isPanelCollapsed:A,reevaluatePanelConstraints:C,registerPanel:O,resizePanel:M,unregisterPanel:L}=w,j=GO(i),B=y.useRef({callbacks:{onCollapse:f,onExpand:m,onResize:h},constraints:{collapsedSize:n,collapsible:r,defaultSize:a,maxSize:l,minSize:u},id:j,idIsFromProps:i!==void 0,order:g});y.useRef({didLogMissingDefaultSizeWarning:!1}),ic(()=>{const{callbacks:Z,constraints:te}=B.current,V={...te};B.current.id=j,B.current.idIsFromProps=i!==void 0,B.current.order=g,Z.onCollapse=f,Z.onExpand=m,Z.onResize=h,te.collapsedSize=n,te.collapsible=r,te.defaultSize=a,te.maxSize=l,te.minSize=u,(V.collapsedSize!==te.collapsedSize||V.collapsible!==te.collapsible||V.maxSize!==te.maxSize||V.minSize!==te.minSize)&&C(B.current,V)}),ic(()=>{const Z=B.current;return O(Z),()=>{L(Z)}},[g,j,O,L]),y.useImperativeHandle(o,()=>({collapse:()=>{S(B.current)},expand:Z=>{_(B.current,Z)},getId(){return j},getSize(){return T(B.current)},isCollapsed(){return A(B.current)},isExpanded(){return!A(B.current)},resize:Z=>{M(B.current,Z)}}),[S,_,T,A,j,M]);const K=k(B.current,a);return y.createElement(E,{...x,children:e,className:t,id:j,style:{...K,...b},[br.groupId]:R,[br.panel]:"",[br.panelCollapsible]:r||void 0,[br.panelId]:j,[br.panelSize]:parseFloat(""+K.flexGrow).toFixed(1)})}const gW=y.forwardRef((e,t)=>y.createElement(hW,{...e,forwardedRef:t}));hW.displayName="Panel";gW.displayName="forwardRef(Panel)";let PT=null,Ey=-1,Ki=null;function p_e(e,t,n){const r=(t&xW)!==0,a=(t&EW)!==0,o=(t&SW)!==0,i=(t&_W)!==0;if(t){if(r)return o?"se-resize":i?"ne-resize":"e-resize";if(a)return o?"sw-resize":i?"nw-resize":"w-resize";if(o)return"s-resize";if(i)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function m_e(){Ki!==null&&(document.head.removeChild(Ki),PT=null,Ki=null,Ey=-1)}function wS(e,t,n){var r,a;const o=p_e(e,t);if(PT!==o){if(PT=o,Ki===null&&(Ki=document.createElement("style"),document.head.appendChild(Ki)),Ey>=0){var i;(i=Ki.sheet)===null||i===void 0||i.removeRule(Ey)}Ey=(r=(a=Ki.sheet)===null||a===void 0?void 0:a.insertRule(`*{cursor: ${o} !important;}`))!==null&&r!==void 0?r:-1}}function bW(e){return e.type==="keydown"}function yW(e){return e.type.startsWith("pointer")}function vW(e){return e.type.startsWith("mouse")}function zw(e){if(yW(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(vW(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function h_e(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function g_e(e,t,n){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function b_e(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:_F(e),b:_F(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),r=e;tn(r,"Stacking order can only be calculated for elements with a common ancestor");const a={a:SF(EF(n.a)),b:SF(EF(n.b))};if(a.a===a.b){const o=r.childNodes,i={a:n.a.at(-1),b:n.b.at(-1)};let l=o.length;for(;l--;){const u=o[l];if(u===i.a)return 1;if(u===i.b)return-1}}return Math.sign(a.a-a.b)}const y_e=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function v_e(e){var t;const n=getComputedStyle((t=wW(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function w_e(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||v_e(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||y_e.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function EF(e){let t=e.length;for(;t--;){const n=e[t];if(tn(n,"Missing node"),w_e(n))return n}return null}function SF(e){return e&&Number(getComputedStyle(e).zIndex)||0}function _F(e){const t=[];for(;e;)t.push(e),e=wW(e);return t}function wW(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const xW=1,EW=2,SW=4,_W=8,x_e=h_e()==="coarse";let Bo=[],ad=!1,Yi=new Map,Fw=new Map;const Pm=new Set;function E_e(e,t,n,r,a){var o;const{ownerDocument:i}=t,l={direction:n,element:t,hitAreaMargins:r,setResizeHandlerState:a},u=(o=Yi.get(i))!==null&&o!==void 0?o:0;return Yi.set(i,u+1),Pm.add(l),wv(),function(){var m;Fw.delete(e),Pm.delete(l);const h=(m=Yi.get(i))!==null&&m!==void 0?m:1;if(Yi.set(i,h-1),wv(),h===1&&Yi.delete(i),Bo.includes(l)){const g=Bo.indexOf(l);g>=0&&Bo.splice(g,1),Bw(),a("up",!0,null)}}}function S_e(e){const{target:t}=e,{x:n,y:r}=zw(e);ad=!0,WO({target:t,x:n,y:r}),wv(),Bo.length>0&&(xv("down",e),Bw(),e.preventDefault(),TW(t)||e.stopImmediatePropagation())}function xS(e){const{x:t,y:n}=zw(e);if(ad&&e.type!=="pointerleave"&&e.buttons===0&&(ad=!1,xv("up",e)),!ad){const{target:r}=e;WO({target:r,x:t,y:n})}xv("move",e),Bw(),Bo.length>0&&e.preventDefault()}function ES(e){const{target:t}=e,{x:n,y:r}=zw(e);Fw.clear(),ad=!1,Bo.length>0&&(e.preventDefault(),TW(t)||e.stopImmediatePropagation()),xv("up",e),WO({target:t,x:n,y:r}),Bw(),wv()}function TW(e){let t=e;for(;t;){if(t.hasAttribute(br.resizeHandle))return!0;t=t.parentElement}return!1}function WO({target:e,x:t,y:n}){Bo.splice(0);let r=null;(e instanceof HTMLElement||e instanceof SVGElement)&&(r=e),Pm.forEach(a=>{const{element:o,hitAreaMargins:i}=a,l=o.getBoundingClientRect(),{bottom:u,left:f,right:m,top:h}=l,g=x_e?i.coarse:i.fine;if(t>=f-g&&t<=m+g&&n>=h-g&&n<=u+g){if(r!==null&&document.contains(r)&&o!==r&&!o.contains(r)&&!r.contains(o)&&b_e(r,o)>0){let E=r,x=!1;for(;E&&!E.contains(o);){if(g_e(E.getBoundingClientRect(),l)){x=!0;break}E=E.parentElement}if(x)return}Bo.push(a)}})}function SS(e,t){Fw.set(e,t)}function Bw(){let e=!1,t=!1;Bo.forEach(r=>{const{direction:a}=r;a==="horizontal"?e=!0:t=!0});let n=0;Fw.forEach(r=>{n|=r}),e&&t?wS("intersection",n):e?wS("horizontal",n):t?wS("vertical",n):m_e()}let _S;function wv(){var e;(e=_S)===null||e===void 0||e.abort(),_S=new AbortController;const t={capture:!0,signal:_S.signal};Pm.size&&(ad?(Bo.length>0&&Yi.forEach((n,r)=>{const{body:a}=r;n>0&&(a.addEventListener("contextmenu",ES,t),a.addEventListener("pointerleave",xS,t),a.addEventListener("pointermove",xS,t))}),Yi.forEach((n,r)=>{const{body:a}=r;a.addEventListener("pointerup",ES,t),a.addEventListener("pointercancel",ES,t)})):Yi.forEach((n,r)=>{const{body:a}=r;n>0&&(a.addEventListener("pointerdown",S_e,t),a.addEventListener("pointermove",xS,t))}))}function xv(e,t){Pm.forEach(n=>{const{setResizeHandlerState:r}=n,a=Bo.includes(n);r(e,a,t)})}function __e(){const[e,t]=y.useState(0);return y.useCallback(()=>t(n=>n+1),[])}function tn(e,t){if(!e)throw console.error(t),Error(t)}function vc(e,t,n=VO){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function Ws(e,t,n=VO){return vc(e,t,n)===0}function Qa(e,t,n){return vc(e,t,n)===0}function T_e(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++){const a=e[r],o=t[r];if(!Qa(a,o,n))return!1}return!0}function Wu({panelConstraints:e,panelIndex:t,size:n}){const r=e[t];tn(r!=null,`Panel constraints not found for index ${t}`);let{collapsedSize:a=0,collapsible:o,maxSize:i=100,minSize:l=0}=r;if(vc(n,l)<0)if(o){const u=(a+l)/2;vc(n,u)<0?n=a:n=l}else n=l;return n=Math.min(i,n),n=parseFloat(n.toFixed(VO)),n}function Lp({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:r,prevLayout:a,trigger:o}){if(Qa(e,0))return t;const i=[...t],[l,u]=r;tn(l!=null,"Invalid first pivot index"),tn(u!=null,"Invalid second pivot index");let f=0;if(o==="keyboard"){{const h=e<0?u:l,g=n[h];tn(g,`Panel constraints not found for index ${h}`);const{collapsedSize:b=0,collapsible:E,minSize:x=0}=g;if(E){const w=t[h];if(tn(w!=null,`Previous layout not found for panel index ${h}`),Qa(w,b)){const S=x-w;vc(S,Math.abs(e))>0&&(e=e<0?0-S:S)}}}{const h=e<0?l:u,g=n[h];tn(g,`No panel constraints found for index ${h}`);const{collapsedSize:b=0,collapsible:E,minSize:x=0}=g;if(E){const w=t[h];if(tn(w!=null,`Previous layout not found for panel index ${h}`),Qa(w,x)){const S=w-b;vc(S,Math.abs(e))>0&&(e=e<0?0-S:S)}}}}{const h=e<0?1:-1;let g=e<0?u:l,b=0;for(;;){const x=t[g];tn(x!=null,`Previous layout not found for panel index ${g}`);const S=Wu({panelConstraints:n,panelIndex:g,size:100})-x;if(b+=S,g+=h,g<0||g>=n.length)break}const E=Math.min(Math.abs(e),Math.abs(b));e=e<0?0-E:E}{let g=e<0?l:u;for(;g>=0&&g<n.length;){const b=Math.abs(e)-Math.abs(f),E=t[g];tn(E!=null,`Previous layout not found for panel index ${g}`);const x=E-b,w=Wu({panelConstraints:n,panelIndex:g,size:x});if(!Qa(E,w)&&(f+=E-w,i[g]=w,f.toFixed(3).localeCompare(Math.abs(e).toFixed(3),void 0,{numeric:!0})>=0))break;e<0?g--:g++}}if(T_e(a,i))return a;{const h=e<0?u:l,g=t[h];tn(g!=null,`Previous layout not found for panel index ${h}`);const b=g+f,E=Wu({panelConstraints:n,panelIndex:h,size:b});if(i[h]=E,!Qa(E,b)){let x=b-E,S=e<0?u:l;for(;S>=0&&S<n.length;){const _=i[S];tn(_!=null,`Previous layout not found for panel index ${S}`);const T=_+x,k=Wu({panelConstraints:n,panelIndex:S,size:T});if(Qa(_,k)||(x-=k-_,i[S]=k),Qa(x,0))break;e>0?S--:S++}}}const m=i.reduce((h,g)=>g+h,0);return Qa(m,100)?i:a}function N_e({layout:e,panelsArray:t,pivotIndices:n}){let r=0,a=100,o=0,i=0;const l=n[0];tn(l!=null,"No pivot index found"),t.forEach((h,g)=>{const{constraints:b}=h,{maxSize:E=100,minSize:x=0}=b;g===l?(r=x,a=E):(o+=x,i+=E)});const u=Math.min(a,100-o),f=Math.max(r,100-i),m=e[l];return{valueMax:u,valueMin:f,valueNow:m}}function $m(e,t=document){return Array.from(t.querySelectorAll(`[${br.resizeHandleId}][data-panel-group-id="${e}"]`))}function NW(e,t,n=document){const a=$m(e,n).findIndex(o=>o.getAttribute(br.resizeHandleId)===t);return a??null}function CW(e,t,n){const r=NW(e,t,n);return r!=null?[r,r+1]:[-1,-1]}function C_e(e){return e instanceof HTMLElement?!0:typeof e=="object"&&e!==null&&"tagName"in e&&"getAttribute"in e}function RW(e,t=document){if(C_e(t)&&t.dataset.panelGroupId==e)return t;const n=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return n||null}function Hw(e,t=document){const n=t.querySelector(`[${br.resizeHandleId}="${e}"]`);return n||null}function R_e(e,t,n,r=document){var a,o,i,l;const u=Hw(t,r),f=$m(e,r),m=u?f.indexOf(u):-1,h=(a=(o=n[m])===null||o===void 0?void 0:o.id)!==null&&a!==void 0?a:null,g=(i=(l=n[m+1])===null||l===void 0?void 0:l.id)!==null&&i!==void 0?i:null;return[h,g]}function k_e({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:r,panelDataArray:a,panelGroupElement:o,setLayout:i}){y.useRef({didWarnAboutMissingResizeHandle:!1}),ic(()=>{if(!o)return;const l=$m(n,o);for(let u=0;u<a.length-1;u++){const{valueMax:f,valueMin:m,valueNow:h}=N_e({layout:r,panelsArray:a,pivotIndices:[u,u+1]}),g=l[u];if(g!=null){const b=a[u];tn(b,`No panel data found for index "${u}"`),g.setAttribute("aria-controls",b.id),g.setAttribute("aria-valuemax",""+Math.round(f)),g.setAttribute("aria-valuemin",""+Math.round(m)),g.setAttribute("aria-valuenow",h!=null?""+Math.round(h):"")}}return()=>{l.forEach((u,f)=>{u.removeAttribute("aria-controls"),u.removeAttribute("aria-valuemax"),u.removeAttribute("aria-valuemin"),u.removeAttribute("aria-valuenow")})}},[n,r,a,o]),y.useEffect(()=>{if(!o)return;const l=t.current;tn(l,"Eager values not found");const{panelDataArray:u}=l,f=RW(n,o);tn(f!=null,`No group found for id "${n}"`);const m=$m(n,o);tn(m,`No resize handles found for group id "${n}"`);const h=m.map(g=>{const b=g.getAttribute(br.resizeHandleId);tn(b,"Resize handle element has no handle id attribute");const[E,x]=R_e(n,b,u,o);if(E==null||x==null)return()=>{};const w=S=>{if(!S.defaultPrevented)switch(S.key){case"Enter":{S.preventDefault();const _=u.findIndex(T=>T.id===E);if(_>=0){const T=u[_];tn(T,`No panel data found for index ${_}`);const k=r[_],{collapsedSize:R=0,collapsible:A,minSize:C=0}=T.constraints;if(k!=null&&A){const O=Lp({delta:Qa(k,R)?C-R:R-k,initialLayout:r,panelConstraints:u.map(M=>M.constraints),pivotIndices:CW(n,b,o),prevLayout:r,trigger:"keyboard"});r!==O&&i(O)}}break}}};return g.addEventListener("keydown",w),()=>{g.removeEventListener("keydown",w)}});return()=>{h.forEach(g=>g())}},[o,e,t,n,r,a,i])}function TF(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function kW(e,t){const n=e==="horizontal",{x:r,y:a}=zw(t);return n?r:a}function A_e(e,t,n,r,a){const o=n==="horizontal",i=Hw(t,a);tn(i,`No resize handle element found for id "${t}"`);const l=i.getAttribute(br.groupId);tn(l,"Resize handle element has no group id attribute");let{initialCursorPosition:u}=r;const f=kW(n,e),m=RW(l,a);tn(m,`No group element found for id "${l}"`);const h=m.getBoundingClientRect(),g=o?h.width:h.height;return(f-u)/g*100}function I_e(e,t,n,r,a,o){if(bW(e)){const i=n==="horizontal";let l=0;e.shiftKey?l=100:a!=null?l=a:l=10;let u=0;switch(e.key){case"ArrowDown":u=i?0:l;break;case"ArrowLeft":u=i?-l:0;break;case"ArrowRight":u=i?l:0;break;case"ArrowUp":u=i?0:-l;break;case"End":u=100;break;case"Home":u=-100;break}return u}else return r==null?0:A_e(e,t,n,r,o)}function O_e({panelDataArray:e}){const t=Array(e.length),n=e.map(o=>o.constraints);let r=0,a=100;for(let o=0;o<e.length;o++){const i=n[o];tn(i,`Panel constraints not found for index ${o}`);const{defaultSize:l}=i;l!=null&&(r++,t[o]=l,a-=l)}for(let o=0;o<e.length;o++){const i=n[o];tn(i,`Panel constraints not found for index ${o}`);const{defaultSize:l}=i;if(l!=null)continue;const u=e.length-r,f=a/u;r++,t[o]=f,a-=f}return t}function vu(e,t,n){t.forEach((r,a)=>{const o=e[a];tn(o,`Panel data not found for index ${a}`);const{callbacks:i,constraints:l,id:u}=o,{collapsedSize:f=0,collapsible:m}=l,h=n[u];if(h==null||r!==h){n[u]=r;const{onCollapse:g,onExpand:b,onResize:E}=i;E&&E(r,h),m&&(g||b)&&(b&&(h==null||Ws(h,f))&&!Ws(r,f)&&b(),g&&(h==null||!Ws(h,f))&&Ws(r,f)&&g())}})}function Wb(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!=t[n])return!1;return!0}function D_e({defaultSize:e,dragState:t,layout:n,panelData:r,panelIndex:a,precision:o=3}){const i=n[a];let l;return i==null?l=e!=null?e.toFixed(o):"1":r.length===1?l="1":l=i.toFixed(o),{flexBasis:0,flexGrow:l,flexShrink:1,overflow:"hidden",pointerEvents:t!==null?"none":void 0}}function L_e(e,t=10){let n=null;return(...a)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...a)},t)}}function NF(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function AW(e){return`react-resizable-panels:${e}`}function IW(e){return e.map(t=>{const{constraints:n,id:r,idIsFromProps:a,order:o}=t;return a?r:o?`${o}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function OW(e,t){try{const n=AW(e),r=t.getItem(n);if(r){const a=JSON.parse(r);if(typeof a=="object"&&a!=null)return a}}catch{}return null}function M_e(e,t,n){var r,a;const o=(r=OW(e,n))!==null&&r!==void 0?r:{},i=IW(t);return(a=o[i])!==null&&a!==void 0?a:null}function j_e(e,t,n,r,a){var o;const i=AW(e),l=IW(t),u=(o=OW(e,a))!==null&&o!==void 0?o:{};u[l]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{a.setItem(i,JSON.stringify(u))}catch(f){console.error(f)}}function CF({layout:e,panelConstraints:t}){const n=[...e],r=n.reduce((o,i)=>o+i,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(o=>`${o}%`).join(", ")}`);if(!Qa(r,100)&&n.length>0)for(let o=0;o<t.length;o++){const i=n[o];tn(i!=null,`No layout data found for index ${o}`);const l=100/r*i;n[o]=l}let a=0;for(let o=0;o<t.length;o++){const i=n[o];tn(i!=null,`No layout data found for index ${o}`);const l=Wu({panelConstraints:t,panelIndex:o,size:i});i!=l&&(a+=i-l,n[o]=l)}if(!Qa(a,0))for(let o=0;o<t.length;o++){const i=n[o];tn(i!=null,`No layout data found for index ${o}`);const l=i+a,u=Wu({panelConstraints:t,panelIndex:o,size:l});if(i!==u&&(a-=u-i,n[o]=u,Qa(a,0)))break}return n}const P_e=100,Mp={getItem:e=>(NF(Mp),Mp.getItem(e)),setItem:(e,t)=>{NF(Mp),Mp.setItem(e,t)}},RF={};function DW({autoSaveId:e=null,children:t,className:n="",direction:r,forwardedRef:a,id:o=null,onLayout:i=null,keyboardResizeBy:l=null,storage:u=Mp,style:f,tagName:m="div",...h}){const g=GO(o),b=y.useRef(null),[E,x]=y.useState(null),[w,S]=y.useState([]),_=__e(),T=y.useRef({}),k=y.useRef(new Map),R=y.useRef(0),A=y.useRef({autoSaveId:e,direction:r,dragState:E,id:g,keyboardResizeBy:l,onLayout:i,storage:u}),C=y.useRef({layout:w,panelDataArray:[],panelDataArrayChanged:!1});y.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),y.useImperativeHandle(a,()=>({getId:()=>A.current.id,getLayout:()=>{const{layout:U}=C.current;return U},setLayout:U=>{const{onLayout:D}=A.current,{layout:$,panelDataArray:G}=C.current,W=CF({layout:U,panelConstraints:G.map(re=>re.constraints)});TF($,W)||(S(W),C.current.layout=W,D&&D(W),vu(G,W,T.current))}}),[]),ic(()=>{A.current.autoSaveId=e,A.current.direction=r,A.current.dragState=E,A.current.id=g,A.current.onLayout=i,A.current.storage=u}),k_e({committedValuesRef:A,eagerValuesRef:C,groupId:g,layout:w,panelDataArray:C.current.panelDataArray,setLayout:S,panelGroupElement:b.current}),y.useEffect(()=>{const{panelDataArray:U}=C.current;if(e){if(w.length===0||w.length!==U.length)return;let D=RF[e];D==null&&(D=L_e(j_e,P_e),RF[e]=D);const $=[...U],G=new Map(k.current);D(e,$,G,w,u)}},[e,w,u]),y.useEffect(()=>{});const O=y.useCallback(U=>{const{onLayout:D}=A.current,{layout:$,panelDataArray:G}=C.current;if(U.constraints.collapsible){const W=G.map(ne=>ne.constraints),{collapsedSize:re=0,panelSize:pe,pivotIndices:me}=Wl(G,U,$);if(tn(pe!=null,`Panel size not found for panel "${U.id}"`),!Ws(pe,re)){k.current.set(U.id,pe);const J=ku(G,U)===G.length-1?pe-re:re-pe,X=Lp({delta:J,initialLayout:$,panelConstraints:W,pivotIndices:me,prevLayout:$,trigger:"imperative-api"});Wb($,X)||(S(X),C.current.layout=X,D&&D(X),vu(G,X,T.current))}}},[]),M=y.useCallback((U,D)=>{const{onLayout:$}=A.current,{layout:G,panelDataArray:W}=C.current;if(U.constraints.collapsible){const re=W.map(se=>se.constraints),{collapsedSize:pe=0,panelSize:me=0,minSize:ne=0,pivotIndices:J}=Wl(W,U,G),X=D??ne;if(Ws(me,pe)){const se=k.current.get(U.id),he=se!=null&&se>=X?se:X,Be=ku(W,U)===W.length-1?me-he:he-me,$e=Lp({delta:Be,initialLayout:G,panelConstraints:re,pivotIndices:J,prevLayout:G,trigger:"imperative-api"});Wb(G,$e)||(S($e),C.current.layout=$e,$&&$($e),vu(W,$e,T.current))}}},[]),L=y.useCallback(U=>{const{layout:D,panelDataArray:$}=C.current,{panelSize:G}=Wl($,U,D);return tn(G!=null,`Panel size not found for panel "${U.id}"`),G},[]),j=y.useCallback((U,D)=>{const{panelDataArray:$}=C.current,G=ku($,U);return D_e({defaultSize:D,dragState:E,layout:w,panelData:$,panelIndex:G})},[E,w]),B=y.useCallback(U=>{const{layout:D,panelDataArray:$}=C.current,{collapsedSize:G=0,collapsible:W,panelSize:re}=Wl($,U,D);return tn(re!=null,`Panel size not found for panel "${U.id}"`),W===!0&&Ws(re,G)},[]),K=y.useCallback(U=>{const{layout:D,panelDataArray:$}=C.current,{collapsedSize:G=0,collapsible:W,panelSize:re}=Wl($,U,D);return tn(re!=null,`Panel size not found for panel "${U.id}"`),!W||vc(re,G)>0},[]),Z=y.useCallback(U=>{const{panelDataArray:D}=C.current;D.push(U),D.sort(($,G)=>{const W=$.order,re=G.order;return W==null&&re==null?0:W==null?-1:re==null?1:W-re}),C.current.panelDataArrayChanged=!0,_()},[_]);ic(()=>{if(C.current.panelDataArrayChanged){C.current.panelDataArrayChanged=!1;const{autoSaveId:U,onLayout:D,storage:$}=A.current,{layout:G,panelDataArray:W}=C.current;let re=null;if(U){const me=M_e(U,W,$);me&&(k.current=new Map(Object.entries(me.expandToSizes)),re=me.layout)}re==null&&(re=O_e({panelDataArray:W}));const pe=CF({layout:re,panelConstraints:W.map(me=>me.constraints)});TF(G,pe)||(S(pe),C.current.layout=pe,D&&D(pe),vu(W,pe,T.current))}}),ic(()=>{const U=C.current;return()=>{U.layout=[]}},[]);const te=y.useCallback(U=>{let D=!1;const $=b.current;return $&&window.getComputedStyle($,null).getPropertyValue("direction")==="rtl"&&(D=!0),function(W){W.preventDefault();const re=b.current;if(!re)return()=>null;const{direction:pe,dragState:me,id:ne,keyboardResizeBy:J,onLayout:X}=A.current,{layout:se,panelDataArray:he}=C.current,{initialLayout:Te}=me??{},Be=CW(ne,U,re);let $e=I_e(W,U,pe,me,J,re);const Ge=pe==="horizontal";Ge&&D&&($e=-$e);const dt=he.map(rt=>rt.constraints),Ve=Lp({delta:$e,initialLayout:Te??se,panelConstraints:dt,pivotIndices:Be,prevLayout:se,trigger:bW(W)?"keyboard":"mouse-or-touch"}),ct=!Wb(se,Ve);(yW(W)||vW(W))&&R.current!=$e&&(R.current=$e,!ct&&$e!==0?Ge?SS(U,$e<0?xW:EW):SS(U,$e<0?SW:_W):SS(U,0)),ct&&(S(Ve),C.current.layout=Ve,X&&X(Ve),vu(he,Ve,T.current))}},[]),V=y.useCallback((U,D)=>{const{onLayout:$}=A.current,{layout:G,panelDataArray:W}=C.current,re=W.map(se=>se.constraints),{panelSize:pe,pivotIndices:me}=Wl(W,U,G);tn(pe!=null,`Panel size not found for panel "${U.id}"`);const J=ku(W,U)===W.length-1?pe-D:D-pe,X=Lp({delta:J,initialLayout:G,panelConstraints:re,pivotIndices:me,prevLayout:G,trigger:"imperative-api"});Wb(G,X)||(S(X),C.current.layout=X,$&&$(X),vu(W,X,T.current))},[]),Y=y.useCallback((U,D)=>{const{layout:$,panelDataArray:G}=C.current,{collapsedSize:W=0,collapsible:re}=D,{collapsedSize:pe=0,collapsible:me,maxSize:ne=100,minSize:J=0}=U.constraints,{panelSize:X}=Wl(G,U,$);X!=null&&(re&&me&&Ws(X,W)?Ws(W,pe)||V(U,pe):X<J?V(U,J):X>ne&&V(U,ne))},[V]),F=y.useCallback((U,D)=>{const{direction:$}=A.current,{layout:G}=C.current;if(!b.current)return;const W=Hw(U,b.current);tn(W,`Drag handle element not found for id "${U}"`);const re=kW($,D);x({dragHandleId:U,dragHandleRect:W.getBoundingClientRect(),initialCursorPosition:re,initialLayout:G})},[]),ae=y.useCallback(()=>{x(null)},[]),ee=y.useCallback(U=>{const{panelDataArray:D}=C.current,$=ku(D,U);$>=0&&(D.splice($,1),delete T.current[U.id],C.current.panelDataArrayChanged=!0,_())},[_]),P=y.useMemo(()=>({collapsePanel:O,direction:r,dragState:E,expandPanel:M,getPanelSize:L,getPanelStyle:j,groupId:g,isPanelCollapsed:B,isPanelExpanded:K,reevaluatePanelConstraints:Y,registerPanel:Z,registerResizeHandle:te,resizePanel:V,startDragging:F,stopDragging:ae,unregisterPanel:ee,panelGroupElement:b.current}),[O,E,r,M,L,j,g,B,K,Y,Z,te,V,F,ae,ee]),H={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return y.createElement(Uw.Provider,{value:P},y.createElement(m,{...h,children:t,className:n,id:o,ref:b,style:{...H,...f},[br.group]:"",[br.groupDirection]:r,[br.groupId]:g}))}const LW=y.forwardRef((e,t)=>y.createElement(DW,{...e,forwardedRef:t}));DW.displayName="PanelGroup";LW.displayName="forwardRef(PanelGroup)";function ku(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function Wl(e,t,n){const r=ku(e,t),o=r===e.length-1?[r-1,r]:[r,r+1],i=n[r];return{...t.constraints,panelSize:i,pivotIndices:o}}function $_e({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:r}){y.useEffect(()=>{if(e||n==null||r==null)return;const a=Hw(t,r);if(a==null)return;const o=i=>{if(!i.defaultPrevented)switch(i.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{i.preventDefault(),n(i);break}case"F6":{i.preventDefault();const l=a.getAttribute(br.groupId);tn(l,`No group element found for id "${l}"`);const u=$m(l,r),f=NW(l,t,r);tn(f!==null,`No resize element found for id "${t}"`);const m=i.shiftKey?f>0?f-1:u.length-1:f+1<u.length?f+1:0;u[m].focus();break}}};return a.addEventListener("keydown",o),()=>{a.removeEventListener("keydown",o)}},[r,e,t,n])}function MW({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:r,id:a,onBlur:o,onClick:i,onDragging:l,onFocus:u,onPointerDown:f,onPointerUp:m,style:h={},tabIndex:g=0,tagName:b="div",...E}){var x,w;const S=y.useRef(null),_=y.useRef({onClick:i,onDragging:l,onPointerDown:f,onPointerUp:m});y.useEffect(()=>{_.current.onClick=i,_.current.onDragging=l,_.current.onPointerDown=f,_.current.onPointerUp=m});const T=y.useContext(Uw);if(T===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:k,groupId:R,registerResizeHandle:A,startDragging:C,stopDragging:O,panelGroupElement:M}=T,L=GO(a),[j,B]=y.useState("inactive"),[K,Z]=y.useState(!1),[te,V]=y.useState(null),Y=y.useRef({state:j});ic(()=>{Y.current.state=j}),y.useEffect(()=>{if(n)V(null);else{const P=A(L);V(()=>P)}},[n,L,A]);const F=(x=r?.coarse)!==null&&x!==void 0?x:15,ae=(w=r?.fine)!==null&&w!==void 0?w:5;y.useEffect(()=>{if(n||te==null)return;const P=S.current;tn(P,"Element ref not attached");let H=!1;return E_e(L,P,k,{coarse:F,fine:ae},(D,$,G)=>{if(!$){B("inactive");return}switch(D){case"down":{B("drag"),H=!1,tn(G,'Expected event to be defined for "down" action'),C(L,G);const{onDragging:W,onPointerDown:re}=_.current;W?.(!0),re?.();break}case"move":{const{state:W}=Y.current;H=!0,W!=="drag"&&B("hover"),tn(G,'Expected event to be defined for "move" action'),te(G);break}case"up":{B("hover"),O();const{onClick:W,onDragging:re,onPointerUp:pe}=_.current;re?.(!1),pe?.(),H||W?.();break}}})},[F,k,n,ae,A,L,te,C,O]),$_e({disabled:n,handleId:L,resizeHandler:te,panelGroupElement:M});const ee={touchAction:"none",userSelect:"none"};return y.createElement(b,{...E,children:e,className:t,id:a,onBlur:()=>{Z(!1),o?.()},onFocus:()=>{Z(!0),u?.()},ref:S,role:"separator",style:{...ee,...h},tabIndex:g,[br.groupDirection]:k,[br.groupId]:R,[br.resizeHandle]:"",[br.resizeHandleActive]:j==="drag"?"pointer":K?"keyboard":void 0,[br.resizeHandleEnabled]:!n,[br.resizeHandleId]:L,[br.resizeHandleState]:j})}MW.displayName="PanelResizeHandle";function Ta({className:e,...t}){return d.jsx(LW,{"data-slot":"resizable-panel-group",className:Ue("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t})}function Yn({...e}){return d.jsx(gW,{"data-slot":"resizable-panel",...e})}function Ho({withHandle:e,className:t,...n}){return d.jsx(MW,{"data-slot":"resizable-handle",className:Ue("bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...n,children:e&&d.jsx("div",{className:"bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border",children:d.jsx(Uue,{className:"size-2.5"})})})}function xh({className:e,...t}){return d.jsx("kbd",{"data-slot":"kbd",className:Ue("bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none","[&_svg:not([class*='size-'])]:size-3","[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",e),...t})}function U_e({isSearchExpanded:e,searchQuery:t,filteredNotificationsCount:n,notificationsCount:r,onSearchExpand:a,onSearchChange:o,onSearchBlur:i,onClearAll:l,searchInputRef:u}){return d.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[d.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?d.jsx(Hn,{ref:u,placeholder:"Search notifications...",value:t,onChange:f=>o(f.target.value),onBlur:i,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Notifications"}),d.jsx(Pr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:d.jsx(sf,{className:"h-4 w-4"})})}),d.jsxs(Yt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(xh,{children:"F"})]})]})]})}),d.jsx("div",{className:"flex items-center gap-2",children:d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:l,disabled:r===0,className:"h-8 w-8 p-0",children:d.jsx(ni,{className:"h-4 w-4"})})}),d.jsx(Yt,{side:"bottom",children:"Clear all"})]})})]})}function El({id:e,isSelected:t,isFocused:n,icon:r,title:a,description:o,metadata:i,onClick:l,className:u}){return d.jsx("button",{id:e,type:"button",onClick:l,className:Ue("w-full text-left cursor-pointer p-2 sm:p-4 border-b dark:border-zinc-700 hover:bg-gray-50 dark:hover:bg-zinc-800/50 transition-colors group",t&&"bg-zinc-50 dark:bg-zinc-800 border-l-4 border-l-zinc-500",n&&"ring-2 ring-zinc-500 dark:ring-zinc-400 ring-inset",u),children:d.jsxs("div",{className:"flex items-start gap-2 sm:gap-3",children:[r&&d.jsx("div",{className:"flex-shrink-0 mt-1",children:d.jsx("div",{className:Ue("p-2.5 rounded-full transition-colors",t?"bg-zinc-500 dark:bg-zinc-100/80 text-zinc-100 dark:text-zinc-900":"bg-gray-100 dark:bg-zinc-700 text-gray-600 dark:text-gray-400 group-hover:bg-gray-200 dark:group-hover:bg-zinc-600"),children:r})}),d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsx("div",{className:"flex items-center gap-2 mb-1",children:d.jsx("h3",{className:Ue("font-medium truncate font-mono text-sm"),children:a})}),o&&d.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 line-clamp-2",children:o})]})]})})}function z_e({notifications:e,selectedNotification:t,onNotificationSelect:n,focusedIndex:r,formatRelativeTime:a,listRef:o}){return e.length===0?d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx(of,{vertical:!0,noBorder:!0,message:"No notifications yet"})}):d.jsx("div",{ref:o,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((i,l)=>d.jsx(El,{id:`notification-${i.id}`,isSelected:t?.id===i.id,isFocused:r===l,title:d.jsxs("span",{className:"flex items-center gap-3",children:[i.method,!i.read&&d.jsx("span",{className:"size-1.5 block rounded-full bg-orange-500"})]}),description:(()=>{const u=a(i.timestamp),f=i.params&&Object.keys(i.params).length>0?Object.keys(i.params).length:0,m=f>0?` | ${f} param${f>1?"s":""}`:"";return u+m})(),onClick:()=>n(i)},i.id))})}function F_e({notification:e,previewMode:t,onTogglePreview:n,onCopy:r,onDownload:a,onFullscreen:o,isCopied:i=!1,onClose:l}){return e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:"flex-shrink-0 px-4 py-3 border-b border-gray-200 dark:border-zinc-700 flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(um,{className:"h-3 w-3 text-gray-400"}),d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleTimeString()})]}),d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:e.formatRelativeTime(e.timestamp)})]}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsxs(Me,{variant:"ghost",size:"sm",onClick:n,className:t?"":"text-purple-600 dark:text-purple-400",children:[t?d.jsx(YN,{className:"h-4 w-4 mr-1"}):d.jsx(UH,{className:"h-4 w-4 mr-1"}),t?"JSON":"Formatted"]}),d.jsx(Me,{variant:"ghost",size:"sm",onClick:r,children:i?d.jsx(Or,{className:"h-4 w-4"}):d.jsx(wr,{className:"h-4 w-4"})}),d.jsx(Me,{variant:"ghost",size:"sm",onClick:a,children:d.jsx(th,{className:"h-4 w-4"})}),d.jsx(Me,{variant:"ghost",size:"sm",onClick:o,children:d.jsx(fm,{className:"h-4 w-4"})}),l&&d.jsx(Me,{variant:"ghost",size:"sm",onClick:l,children:d.jsx(vs,{className:"h-4 w-4"})})]})]}),d.jsx("div",{className:"flex-1 overflow-y-auto",children:d.jsx("div",{className:"px-4 pt-4",children:d.jsx(yr,{data:{method:e.method,timestamp:e.timestamp,read:e.read,params:e.params},filename:`notification-${e.method.replace(/[^a-zA-Z0-9]/g,"-")}-${Date.now()}.json`})})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(KN,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select a notification to view details"})]})}function Ev(e){const n=Date.now()-e,r=Math.floor(n/1e3),a=Math.floor(r/60),o=Math.floor(a/60),i=Math.floor(o/24);return r<60?"just now":a<60?`${a}m ago`:o<24?`${o}h ago`:i<7?`${i}d ago`:new Date(e).toLocaleDateString()}function B_e({notifications:e,unreadCount:t,markNotificationRead:n,markAllNotificationsRead:r,clearNotifications:a,serverId:o,isConnected:i}){const[l,u]=y.useState(null),[f,m]=y.useState(""),[h,g]=y.useState(-1),[b,E]=y.useState(!0),[x,w]=y.useState(!1),[S,_]=y.useState(!0),[T,k]=y.useState(!1),R=y.useRef(null),A=y.useRef(null),C=y.useRef(null),O=y.useRef(!1);y.useEffect(()=>{b&&e.length>0&&R.current&&!O.current&&(R.current.scrollTop=0)},[e.length,b]),y.useEffect(()=>{const Y=R.current;if(!Y)return;const F=()=>{Y.scrollTop>0&&(O.current=!0,E(!1))};return Y.addEventListener("scroll",F),()=>Y.removeEventListener("scroll",F)},[]),y.useEffect(()=>{e.length===0&&(O.current=!1,E(!0))},[e.length]),y.useEffect(()=>{l&&!l.read&&n(l.id)},[l,n]),y.useEffect(()=>{x&&C.current&&C.current.focus()},[x]);const M=y.useCallback(()=>{f.trim()||w(!1)},[f]),L=y.useMemo(()=>{if(!f.trim())return e;const Y=f.toLowerCase();return e.filter(F=>F.method.toLowerCase().includes(Y)||JSON.stringify(F.params||{}).toLowerCase().includes(Y))},[e,f]);y.useEffect(()=>{g(-1)},[f]),y.useEffect(()=>{const Y=F=>{const ae=F.target;if(ae.tagName==="INPUT"||ae.tagName==="TEXTAREA"||ae.contentEditable==="true"||F.metaKey||F.ctrlKey||F.altKey)return;const P=L;if(F.key==="ArrowDown")F.preventDefault(),g(H=>{const U=H+1;return U>=P.length?0:U});else if(F.key==="ArrowUp")F.preventDefault(),g(H=>{const U=H-1;return U<0?P.length-1:U});else if(F.key==="Enter"&&h>=0){F.preventDefault();const H=L[h];H&&j(H)}};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[h,L]),y.useEffect(()=>{if(h>=0){const Y=`notification-${L[h]?.id}`,F=document.getElementById(Y);F&&F.scrollIntoView({behavior:"smooth",block:"nearest"})}},[h,L]);const j=y.useCallback(Y=>{u(Y)},[]),B=y.useCallback(()=>{window.confirm("Are you sure you want to clear all notifications? This cannot be undone.")&&(a(),u(null))},[a]),K=y.useCallback(async()=>{if(l)try{await navigator.clipboard.writeText(JSON.stringify({method:l.method,timestamp:l.timestamp,read:l.read,params:l.params},null,2)),k(!0),setTimeout(()=>k(!1),2e3)}catch(Y){console.error("[NotificationsTab] Failed to copy notification:",Y)}},[l]),Z=y.useCallback(()=>{if(l)try{const Y=new globalThis.Blob([JSON.stringify({method:l.method,timestamp:l.timestamp,read:l.read,params:l.params},null,2)],{type:"application/json"}),F=URL.createObjectURL(Y),ae=document.createElement("a");ae.href=F,ae.download=`notification-${Date.now()}.json`,document.body.appendChild(ae),ae.click(),document.body.removeChild(ae),URL.revokeObjectURL(F)}catch(Y){console.error("[NotificationsTab] Failed to download notification:",Y)}},[l]),te=y.useCallback(async()=>{if(A.current)try{document.fullscreenElement?await document.exitFullscreen():await A.current.requestFullscreen()}catch(Y){console.error("[NotificationsTab] Failed to toggle fullscreen:",Y)}},[]),V=l?{method:l.method,params:l.params,timestamp:l.timestamp,read:l.read,formatRelativeTime:Ev}:null;return i?d.jsxs(Ta,{direction:"horizontal",className:"h-full",children:[d.jsx(Yn,{defaultSize:40,minSize:30,children:d.jsx(Ta,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:d.jsxs(Yn,{defaultSize:75,minSize:30,children:[d.jsx(U_e,{isSearchExpanded:x,searchQuery:f,filteredNotificationsCount:L.length,notificationsCount:e.length,onSearchExpand:()=>w(!0),onSearchChange:m,onSearchBlur:M,onClearAll:B,searchInputRef:C}),d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(z_e,{notifications:L,selectedNotification:l,onNotificationSelect:j,focusedIndex:h,formatRelativeTime:Ev,listRef:R})})]})})}),d.jsx(Ho,{}),d.jsx(Yn,{defaultSize:60,minSize:40,children:d.jsx("div",{ref:A,className:"h-full bg-white dark:bg-zinc-900",children:d.jsx(F_e,{notification:V,previewMode:S,onTogglePreview:()=>_(!S),onCopy:K,onDownload:Z,onFullscreen:te,onClose:()=>u(null),isCopied:T})})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(KN,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function KO({serverIds:e,onCountChange:t,onClearRef:n}={}){const[r,a]=y.useState([]),o=y.useRef(null),[i,l]=y.useState(new Set),[u]=y.useState(""),f=b=>{l(E=>{const x=new Set(E);return x.has(b)?x.delete(b):x.add(b),x})},m=async()=>{a([]),l(new Set),t?.(0),e&&e.length>0?e.forEach(b=>Uy(b)):Uy()},h=y.useMemo(()=>!e||e.length===0?"":[...e].sort().join(","),[e]);y.useEffect(()=>(n&&(n.current=m),()=>{n&&(n.current=null)}),[n,m]),y.useEffect(()=>{t?.(r.length)},[r.length,t]),y.useEffect(()=>{console.log("[RPC Logger] Subscribing to RPC logs for servers:",e);const b=SN(),x=(e&&e.length>0?b.filter(S=>e.includes(S.serverId)):b).map(S=>{const _=S.message,T=typeof _?.method=="string"?_.method:_?.result!==void 0?"result":_?.error!==void 0?"error":"unknown";return{id:`${S.timestamp}-${Math.random().toString(36).slice(2)}`,serverId:S.serverId,direction:S.direction.toUpperCase(),method:T,timestamp:S.timestamp,payload:S.message}}).reverse();a(x),t?.(x.length);const w=_N(S=>{if(e&&e.length>0&&!e.includes(S.serverId))return;const _=S.message,T=typeof _?.method=="string"?_.method:_?.result!==void 0?"result":_?.error!==void 0?"error":"unknown",k={id:`${S.timestamp}-${Math.random().toString(36).slice(2)}`,serverId:S.serverId,direction:S.direction.toUpperCase(),method:T,timestamp:S.timestamp,payload:S.message};console.log("[RPC Logger] New RPC log:",{method:T,direction:S.direction,serverId:S.serverId}),a(R=>{const A=[k,...R].slice(0,1e3);return t?.(A.length),A})});return()=>{w(),console.log("[RPC Logger] Unsubscribed from RPC logs")}},[h,t]);const g=y.useMemo(()=>{let b=r;if(e&&e.length>0){const E=new Set(e);b=b.filter(x=>E.has(x.serverId))}if(u.trim()){const E=u.toLowerCase();b=b.filter(x=>x.serverId.toLowerCase().includes(E)||x.method.toLowerCase().includes(E)||x.direction.toLowerCase().includes(E)||JSON.stringify(x.payload).toLowerCase().includes(E))}return b=[...b].sort((E,x)=>new Date(x.timestamp).getTime()-new Date(E.timestamp).getTime()),b},[r,u,e]);return d.jsx("div",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:d.jsx("div",{ref:o,className:"flex-1 min-h-0 overflow-y-auto",children:g.length===0?d.jsxs("div",{className:"text-center py-8",children:[d.jsx("div",{className:"text-xs text-muted-foreground",children:"No messages yet"}),d.jsx("div",{className:"text-[10px] text-muted-foreground mt-1",children:"JSON-RPC messages will appear here"})]}):g.map(b=>{const E=i.has(b.id);return d.jsxs("div",{className:"group hover:bg-muted/50 transition-all duration-200 overflow-hidden",children:[d.jsxs("div",{className:"px-3 py-2 flex items-center gap-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>f(b.id),children:[d.jsx("div",{className:"flex-shrink-0",children:E?d.jsx(hs,{className:"h-3 w-3 text-muted-foreground transition-transform"}):d.jsx(zH,{className:"h-3 w-3 text-muted-foreground transition-transform"})}),d.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[d.jsx("span",{className:"text-muted-foreground font-mono text-xs",children:new Date(b.timestamp).toLocaleTimeString()}),d.jsx("span",{className:`flex items-center justify-center px-1 py-0.5 rounded ${b.direction==="RECEIVE"?"bg-blue-500/10 text-blue-600 dark:text-blue-400":"bg-green-500/10 text-green-600 dark:text-green-400"}`,title:b.direction==="RECEIVE"?"Incoming":"Outgoing",children:b.direction==="RECEIVE"?d.jsx(Zce,{className:"h-3 w-3"}):d.jsx(Xce,{className:"h-3 w-3"})}),d.jsx("span",{className:"text-xs font-mono text-foreground truncate",children:b.method})]})]}),E&&d.jsx("div",{className:"border-t bg-muted/20",children:d.jsx("div",{className:"p-3",children:d.jsx("div",{className:"max-h-[40vh] overflow-auto rounded-sm bg-background/60 p-2",children:d.jsx(yr,{data:b.payload})})})})]},b.id)})})})}function jW({activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabTitle:r,secondaryTabTitle:a,primaryCount:o,secondaryCount:i,secondaryIcon:l,primaryIcon:u,searchPlaceholder:f="Search...",onSearchExpand:m,onSearchChange:h,onSearchBlur:g,onTabSwitch:b,searchInputRef:E,primaryTabName:x}){const w=e===x;return d.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[d.jsx("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:t?d.jsx(Hn,{ref:E,placeholder:f,value:n,onChange:S=>h(S.target.value),onBlur:g,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:w?r:a}),w&&d.jsxs(d.Fragment,{children:[d.jsx(Pr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:o}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:m,className:"h-8 w-8 p-0",children:d.jsx(sf,{className:"h-4 w-4"})})}),d.jsxs(Yt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(xh,{children:"F"})]})]})]})]})}),d.jsxs(Me,{variant:"ghost",size:"sm",onClick:b,className:"gap-2 flex-shrink-0",children:[w?d.jsx(l,{}):d.jsx(u,{}),d.jsx("span",{className:"hidden sm:inline",children:w?a:r}),w&&i>0&&d.jsx(Pr,{className:"bg-purple-500/20 text-purple-600 dark:text-purple-400 border-transparent",variant:"outline",children:i})]})]})}function kF({prompts:e,selectedPrompt:t,onPromptSelect:n,focusedIndex:r}){return e.length===0?d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(pm,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No prompts available"})]}):d.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((a,o)=>d.jsx(El,{id:`prompt-${a.name}`,isSelected:t?.name===a.name,isFocused:r===o,icon:d.jsx(pm,{className:"h-4 w-4"}),title:a.name,description:a.description,metadata:a.arguments&&a.arguments.length>0&&d.jsxs(Pr,{variant:"outline",className:"text-xs border-gray-300 dark:border-zinc-600 text-gray-600 dark:text-gray-400",children:[a.arguments.length," args"]}),onClick:()=>n(a)},a.name))})}function AF({activeTab:e,isSearchExpanded:t,searchQuery:n,filteredPromptsCount:r,savedPromptsCount:a,onSearchExpand:o,onSearchChange:i,onSearchBlur:l,onTabSwitch:u,searchInputRef:f}){return d.jsx(jW,{activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabName:"prompts",secondaryTabName:"saved",primaryTabTitle:"Prompts",secondaryTabTitle:"History",primaryCount:r,secondaryCount:a,primaryIcon:pm,secondaryIcon:um,searchPlaceholder:"Search prompts...",onSearchExpand:o,onSearchChange:i,onSearchBlur:l,onTabSwitch:u,searchInputRef:f})}function IF({savedPrompts:e,selectedPrompt:t,onLoadPrompt:n,onDeletePrompt:r,focusedIndex:a}){return e.length===0?d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(um,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No history"}),d.jsx("p",{className:"text-sm text-gray-400 dark:text-gray-500 mt-1",children:"Prompts you execute will appear here"})]}):d.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((o,i)=>d.jsx(El,{id:`saved-prompt-${o.id}`,isSelected:t?.id===o.id,isFocused:a===i,icon:d.jsx(um,{className:"h-4 w-4"}),title:o.name,description:`${o.promptName} - ${new Date(o.savedAt).toLocaleString()}`,onClick:()=>n(o)},o.id))})}function H_e({selectedPrompt:e,promptArgs:t,onArgChange:n}){const r=e?.arguments||[];if(!(r.length>0))return d.jsx("div",{className:"flex items-center justify-center h-32 text-gray-500 dark:text-gray-400 text-sm",children:"No arguments required"});const o=i=>{const l=i.name,u=t[l],f=typeof u=="string"?u:JSON.stringify(u);return i.type==="boolean"?d.jsxs("div",{className:"space-y-2",children:[d.jsxs(wn,{htmlFor:l,className:"text-sm font-medium",children:[l,i.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsxs("div",{className:"flex items-center space-x-2",children:[d.jsx("input",{id:l,type:"checkbox",checked:!!u,onChange:m=>n(l,m.target.checked),className:"rounded","aria-label":`Toggle ${l}`}),d.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:i.description})]})]},l):i.type==="number"?d.jsxs("div",{className:"space-y-2",children:[d.jsxs(wn,{htmlFor:l,className:"text-sm font-medium",children:[l,i.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsx(Hn,{id:l,type:"number",value:Number(u)||0,onChange:m=>n(l,Number(m.target.value)),placeholder:i.description||`Enter ${l}`}),i.description&&d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:i.description})]},l):i.type==="array"||i.type==="object"?d.jsxs("div",{className:"space-y-2",children:[d.jsxs(wn,{htmlFor:l,className:"text-sm font-medium",children:[l,i.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsx(bc,{id:l,value:f,onChange:m=>{try{const h=JSON.parse(m.target.value);n(l,h)}catch{n(l,m.target.value)}},placeholder:i.description||`Enter ${l} as JSON`,className:"font-mono text-sm min-h-[100px]"}),i.description&&d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:i.description})]},l):d.jsxs("div",{className:"space-y-2",children:[d.jsxs(wn,{htmlFor:l,className:"text-sm font-medium",children:[l,i.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsx(Hn,{id:l,value:f,onChange:m=>n(l,m.target.value),placeholder:i.description||`Enter ${l}`}),i.description&&d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:i.description})]},l)};return d.jsx("div",{className:"space-y-4",children:r.map(i=>o(i))})}function OF({selectedPrompt:e,promptArgs:t,isExecuting:n,isConnected:r,onArgChange:a,onExecute:o,onSave:i}){return y.useEffect(()=>{const l=u=>{(u.metaKey||u.ctrlKey)&&u.key==="Enter"&&e&&!n&&r&&(u.preventDefault(),o())};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[e,n,r,o]),e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsx("div",{className:"flex-shrink-0 p-3 sm:p-6 pt-3 pb-4 pr-3",children:d.jsxs("div",{children:[d.jsxs("div",{className:"flex flex-row items-center justify-between mb-0 gap-2",children:[d.jsx("h3",{className:"text-base sm:text-lg font-semibold",children:e.name}),d.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[d.jsx(Me,{onClick:o,disabled:n||!r,size:"sm",className:"lg:size-default pr-1! gap-0",children:n?d.jsxs(d.Fragment,{children:[d.jsx(gs,{className:"mr-2"}),d.jsx("span",{className:"hidden sm:inline",children:"Executing..."})]}):d.jsxs(d.Fragment,{children:[d.jsx(GH,{className:"h-4 w-4 sm:mr-2"}),d.jsx("span",{className:"hidden sm:inline",children:"Execute"}),d.jsx("span",{className:"hidden sm:inline text-[12px] border text-zinc-300 p-1 rounded-full border-zinc-300 dark:text-zinc-600 dark:border-zinc-500 ml-2",children:"⌘↵"})]})}),d.jsxs(Me,{variant:"outline",onClick:i,disabled:n,size:"sm",className:"lg:size-default gap-2",children:[d.jsx(XN,{className:"h-4 w-4"}),d.jsx("span",{className:"hidden sm:inline",children:"Save"})]})]})]}),e.description&&d.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 leading-relaxed mt-2",children:e.description})]})}),d.jsx("div",{className:"flex-1 overflow-y-auto px-3 sm:px-6 pb-4 pr-3",children:d.jsx(H_e,{selectedPrompt:e,promptArgs:t,onArgChange:a})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"Select a prompt to get started"}),d.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Choose a prompt from the list to view its details and execute it"})]})}function V_e(e){switch(e){case"system":return"default";case"user":return"outline";case"assistant":return"secondary";default:return"outline"}}function G_e(e){return e.charAt(0).toUpperCase()+e.slice(1)}function W_e(e){return typeof e=="string"?e:e.text?e.text:e.type==="resource"&&e.resource?.text?e.resource.text:e.type==="image"?`[Image: ${e.mimeType||"unknown type"}]`:JSON.stringify(e,null,2)}function K_e({message:e,index:t}){const[n,r]=y.useState(!1),a=async()=>{const i=W_e(e.content);await navigator.clipboard.writeText(i),r(!0),setTimeout(()=>r(!1),2e3)},o=()=>{const i=e.content;return typeof i=="string"?d.jsx(vy,{content:i}):i.type==="text"&&i.text?d.jsx(vy,{content:i.text}):i.type==="image"?d.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[d.jsxs("span",{className:"font-mono bg-muted px-2 py-1 rounded",children:["Image: ",i.mimeType||"unknown type"]}),i.data&&d.jsx("img",{src:`data:${i.mimeType};base64,${i.data}`,alt:"Prompt image",className:"max-w-full max-h-[300px] object-contain rounded-lg border border-border mt-2"})]}):i.type==="resource"&&i.resource?d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[d.jsx("span",{className:"text-muted-foreground font-medium",children:"Resource:"}),d.jsx("code",{className:"bg-muted px-2 py-0.5 rounded text-xs font-mono",children:i.resource.uri})]}),i.resource.text&&d.jsx("div",{className:"mt-2",children:d.jsx(vy,{content:i.resource.text})})]}):d.jsx("pre",{className:"bg-muted p-3 rounded-lg text-sm overflow-x-auto",children:d.jsx("code",{children:JSON.stringify(i,null,2)})})};return d.jsxs("div",{className:"border border-border rounded-lg overflow-hidden bg-white dark:bg-zinc-900",children:[d.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-muted/30 border-b border-border",children:[d.jsx(Pr,{variant:V_e(e.role),children:G_e(e.role)}),d.jsx(Me,{variant:"ghost",size:"sm",onClick:a,className:"h-6 px-2",title:"Copy message content",children:n?d.jsx(Or,{className:"h-3.5 w-3.5"}):d.jsx(wr,{className:"h-3.5 w-3.5"})})]}),d.jsx("div",{className:"px-4 py-3",children:o()})]})}function Y_e(e){const n=Date.now()-e,r=Math.floor(n/1e3),a=Math.floor(r/60),o=Math.floor(a/60),i=Math.floor(o/24);return r<10?"now":r<60?`${r}s ago`:a<60?`${a}m ago`:o<24?`${o}h ago`:`${i}d ago`}function Z_e(e){return"isError"in e&&!e.isError?null:"error"in e&&e.error?e.error:"isError"in e&&e.isError?"An error occurred":null}function DF({results:e,copiedResult:t,previewMode:n=!0,onCopy:r,onDelete:a,onFullscreen:o,onTogglePreview:i,onMaximize:l,isMaximized:u=!1}){const[f,m]=y.useState(0),[h,g]=y.useState(""),[b,E]=y.useState(!0),x=e[0],w=x?e.filter(R=>R.promptName===x.promptName):[],S=w[f]||w[0],_=e.findIndex(R=>R===S);if(y.useEffect(()=>{w.length>0&&f>=w.length&&m(0)},[w.length,f]),y.useEffect(()=>{const R=()=>{S&&g(Y_e(S.timestamp))};R();const A=setInterval(R,1e3);return()=>clearInterval(A)},[S]),e.length===0)return d.jsx("div",{className:"flex flex-col h-full bg-white dark:bg-black border-t dark:border-zinc-700",children:d.jsx("div",{className:"flex-1 overflow-y-auto h-full",children:d.jsx("div",{className:"flex items-center justify-center h-full",children:d.jsx("div",{className:"text-center",children:d.jsx(of,{vertical:!0,noBorder:!0,message:"No Results yet"})})})})});const T=S.error||Z_e(S.result),k="messages"in S.result&&Array.isArray(S.result.messages);return d.jsx("div",{className:"flex flex-col h-full bg-white dark:bg-black border-t dark:border-zinc-700",children:d.jsx("div",{className:"flex-1 overflow-y-auto h-full",children:d.jsxs("div",{className:"space-y-0 flex-1 h-full flex flex-col",children:[d.jsxs("div",{className:"flex items-center gap-2 px-4 pt-2 border-b border-gray-200 dark:border-zinc-600 pb-2",children:[d.jsx("h3",{className:"text-sm font-medium hidden sm:block",children:"Response"}),S.duration!==void 0&&d.jsxs("div",{className:"hidden sm:flex items-center gap-1",children:[d.jsx(hm,{className:"h-3 w-3 text-gray-400"}),d.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[S.duration,"ms"]})]}),k&&d.jsx("div",{className:"flex items-center gap-4 sm:ml-4",children:d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>E(!0),className:`text-xs font-medium ${b?"text-black dark:text-white":"text-zinc-500 dark:text-zinc-400"}`,children:"Formatted"}),d.jsx("span",{className:"text-xs text-zinc-400",children:"|"}),d.jsx("button",{onClick:()=>E(!1),className:`text-xs font-medium ${b?"text-zinc-500 dark:text-zinc-400":"text-black dark:text-white"}`,children:"Raw"})]})}),d.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[w.length>1&&d.jsxs("div",{className:"flex items-center gap-2 mr-2",children:[d.jsx(dm,{className:"h-3 w-3 text-gray-400"}),d.jsxs(Zs,{value:f.toString(),onValueChange:R=>m(parseInt(R)),children:[d.jsx(Xs,{className:"h-7 w-[120px] text-xs",children:d.jsx(qs,{})}),d.jsx(Js,{children:w.map((R,A)=>d.jsx(fa,{value:A.toString(),children:A===0?"Latest":`${A+1} call ago`},A))})]})]}),d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 mr-2",children:h}),d.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>r(_,S.result),className:"h-7 w-7 p-0",title:"Copy result",children:t===_?d.jsx(Or,{className:"h-4 w-4"}):d.jsx(wr,{className:"h-4 w-4"})}),a&&d.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>a(_),className:"h-7 w-7 p-0",title:"Delete result",children:d.jsx(ni,{className:"h-4 w-4"})}),o&&d.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>o(_),className:"h-7 w-7 p-0 sm:hidden",title:"Fullscreen",children:d.jsx(fm,{className:"h-4 w-4"})}),l&&d.jsx(Me,{variant:"ghost",size:"sm",onClick:l,className:"h-7 w-7 p-0 hidden sm:flex",title:u?"Restore":"Maximize",children:u?d.jsx(VH,{className:"h-4 w-4"}):d.jsx(fm,{className:"h-4 w-4"})})]})]}),d.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:T?d.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded p-3",children:[d.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Error:"}),d.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:T})]}):b&&k?d.jsx("div",{className:"space-y-3",children:S.result.messages.map((R,A)=>d.jsx(K_e,{message:R,index:A},A))}):d.jsx(yr,{data:S.result,filename:`prompt-result-${S.promptName}-${Date.now()}.json`})})]})})})}const LF="mcp-inspector-saved-prompts";function PW({ref:e,prompts:t,callPrompt:n,serverId:r,isConnected:a}){const[o,i]=y.useState(null),[l,u]=y.useState(null),{selectedPromptName:f,setSelectedPromptName:m}=kc(),[h,g]=y.useState({}),[b,E]=y.useState([]),[x,w]=y.useState(!1),[S,_]=y.useState(null),[T,k]=y.useState(""),[R,A]=y.useState("prompts"),[C,O]=y.useState([]),[M,L]=y.useState(!1),[j,B]=y.useState(""),[K,Z]=y.useState(!1),[te,V]=y.useState(-1),Y=y.useRef(null),[F,ae]=y.useState(!1),[ee,P]=y.useState("list"),[H,U]=y.useState(0),[D,$]=y.useState(!0),[G,W]=y.useState(!1),re=y.useRef(null),pe=y.useRef(null),me=y.useRef(null),ne=y.useRef(null);y.useEffect(()=>{const Ce=()=>{ae(window.innerWidth<1024)};return Ce(),window.addEventListener("resize",Ce),()=>window.removeEventListener("resize",Ce)},[]),y.useEffect(()=>{P(o?"detail":"list")},[o]),y.useEffect(()=>{F&&b.length>0&&!x&&P("response")},[b,x,F]),y.useImperativeHandle(e,()=>({focusSearch:()=>{Z(!0),setTimeout(()=>{Y.current&&Y.current.focus()},0)},blurSearch:()=>{k(""),Z(!1),Y.current&&Y.current.blur()}})),y.useEffect(()=>{try{const Ce=localStorage.getItem(LF);if(Ce){const He=JSON.parse(Ce);O(He)}}catch(Ce){console.error("[PromptsTab] Failed to load saved prompts:",Ce)}},[]);const J=y.useCallback(Ce=>{try{localStorage.setItem(LF,JSON.stringify(Ce))}catch(He){console.error("[PromptsTab] Failed to save prompts:",He)}},[]);y.useEffect(()=>{K&&Y.current&&Y.current.focus()},[K]);const X=y.useCallback(()=>{T.trim()||Z(!1)},[T]),se=y.useMemo(()=>{if(!T.trim())return t;const Ce=T.toLowerCase();return t.filter(He=>He.name.toLowerCase().includes(Ce)||He.description?.toLowerCase().includes(Ce))},[t,T]),he=y.useCallback(Ce=>{i(Ce);const He={};Ce.arguments&&Ce.arguments.forEach(st=>{He[st.name]=""}),g(He)},[]),Te=y.useCallback(Ce=>{const He=t.find(st=>st.name===Ce.promptName);He&&(i(He),g(Ce.args),u(Ce))},[t]);y.useEffect(()=>{V(-1)},[T,R]),y.useEffect(()=>{const Ce=He=>{const st=He.target;if(st.tagName==="INPUT"||st.tagName==="TEXTAREA"||st.contentEditable==="true"||He.metaKey||He.ctrlKey||He.altKey)return;const it=R==="prompts"?se:C;if(He.key==="ArrowDown")He.preventDefault(),V(kt=>{const Nn=kt+1;return Nn>=it.length?0:Nn});else if(He.key==="ArrowUp")He.preventDefault(),V(kt=>{const Nn=kt-1;return Nn<0?it.length-1:Nn});else if(He.key==="Enter"&&te>=0)if(He.preventDefault(),R==="prompts"){const kt=se[te];kt&&he(kt)}else{const kt=C[te];kt&&Te(kt)}};return document.addEventListener("keydown",Ce),()=>document.removeEventListener("keydown",Ce)},[te,se,C,R,he,Te]),y.useEffect(()=>{if(te>=0){const Ce=R==="prompts"?`prompt-${se[te]?.name}`:`saved-prompt-${C[te]?.id}`,He=document.getElementById(Ce);He&&He.scrollIntoView({behavior:"smooth",block:"nearest"})}},[te,se,C,R]),y.useEffect(()=>{if(console.warn("[PromptsTab] Auto-selection effect triggered:",{selectedPromptName:f,promptsCount:t.length,currentSelectedPrompt:o?.name}),f&&t.length>0){const Ce=t.find(He=>He.name===f);if(console.warn("[PromptsTab] Prompt lookup result:",{selectedPromptName:f,promptFound:!!Ce,promptName:Ce?.name,shouldSelect:Ce&&o?.name!==Ce.name}),Ce&&o?.name!==Ce.name){console.warn("[PromptsTab] Selecting prompt:",Ce.name),m(null);const He=setTimeout(()=>{he(Ce);const st=document.getElementById(`prompt-${Ce.name}`);st&&(console.warn("[PromptsTab] Scrolling to prompt element"),st.scrollIntoView({behavior:"smooth",block:"nearest"}))},100);return()=>clearTimeout(He)}}},[f,t,o,he,m]);const Be=y.useCallback((Ce,He)=>{g(st=>({...st,[Ce]:He}))},[]),$e=y.useCallback(async()=>{if(!o||x)return;w(!0);const Ce=Date.now();try{const He=await n(o.name,h),st=Date.now()-Ce;ra.getInstance().capture(new bU({promptName:o.name,serverId:r,success:!0})).catch(()=>{}),E(it=>[{promptName:o.name,args:h,result:He,timestamp:Ce,duration:st},...it])}catch(He){ra.getInstance().capture(new bU({promptName:o.name,serverId:r,success:!1,error:He instanceof Error?He.message:"Unknown error"})).catch(()=>{});const Je={promptName:o.name,args:h,result:null,error:He instanceof Error?He.message:String(He),timestamp:Ce,duration:Date.now()-Ce};E(it=>[...it,{...Je,result:{messages:[]}}])}finally{w(!1)}},[o,h,x,n,r]),Ge=y.useCallback(async(Ce,He)=>{try{await navigator.clipboard.writeText(JSON.stringify(He,null,2)),_(Ce),setTimeout(()=>_(null),2e3)}catch(st){console.error("[PromptsTab] Failed to copy result:",st)}},[]),dt=y.useCallback(Ce=>{E(He=>He.filter((st,Je)=>Je!==Ce))},[]),Ve=y.useCallback(Ce=>{if(F)P("response");else{const He=b[Ce];if(He){const st=window.open("","_blank","width=800,height=600");if(st){const Je=He.result;st.document.write(`
1754
1754
  <html>
1755
1755
  <head>
1756
1756
  <title>${He.promptName} Result</title>
@@ -1780,4 +1780,4 @@ print(f"Available resources: {[resource.name for resource in resources]}")
1780
1780
  <pre>${JSON.stringify(We.result,null,2)}</pre>
1781
1781
  </body>
1782
1782
  </html>
1783
- `),ue.document.close())}},[E]),Nn=y.useCallback(()=>{W?(he.current&&he.current.expand(),Te.current&&Te.current.expand(),re(!1)):(he.current&&he.current.collapse(),Te.current&&Te.current.collapse(),re(!0))},[W]),ot=y.useCallback(()=>{i&&(te(""),K(!0))},[i]),zn=y.useCallback(()=>{if(!i)return;const Ye={id:`${Date.now()}-${Math.random()}`,name:Z.trim()||`${i.name} - ${new Date().toLocaleString()}`,toolName:i.name,args:g,savedAt:Date.now(),serverId:i._serverId,serverName:i._serverName};dt([...L,Ye]),ra.getInstance().capture(new Fce({toolName:i.name,serverId:a})).catch(()=>{}),K(!1),te("")},[i,Z,g,L,dt,a]),qt=y.useCallback(Ye=>{dt(L.filter(We=>We.id!==Ye)),u?.id===Ye&&f(null)},[L,dt,u]);return U?d.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[$!=="list"&&d.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[d.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>{$==="response"?G("detail"):(l(null),G("list"))},className:"p-0 h-8 w-8",children:d.jsx(tw,{className:"h-4 w-4"})}),d.jsxs("div",{className:"flex items-center text-sm font-medium",children:[d.jsx("button",{onClick:()=>{l(null),G("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Tools"}),$==="detail"&&d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),d.jsx("button",{onClick:()=>{G("response")},className:$==="detail"?"text-foreground hover:underline":$==="response"?"text-muted-foreground hover:text-foreground hover:underline cursor-pointer":"text-muted-foreground",children:"Execute"})]}),$==="response"&&d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),d.jsx("span",{className:"text-foreground",children:"Response"})]})]})]}),d.jsx("div",{className:"flex-1 relative overflow-hidden",children:d.jsxs(Rw,{initial:!1,mode:"popLayout",children:[$==="list"&&d.jsxs(Fa.div,{initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 flex flex-col bg-background z-0",children:[d.jsx(GF,{activeTab:O,isSearchExpanded:F,searchQuery:A,filteredToolsCount:Ve.length,savedRequestsCount:L.length,onSearchExpand:()=>ae(!0),onSearchChange:C,onSearchBlur:Ee,onTabSwitch:()=>M(O==="tools"?"saved":"tools"),searchInputRef:H}),O==="tools"?d.jsx(VF,{tools:Ve,selectedTool:i,onToolSelect:ct,focusedIndex:ee}):d.jsx($F,{savedRequests:L,selectedRequest:u,onLoadRequest:rt,onDeleteRequest:qt,focusedIndex:ee})]},"list"),$==="detail"&&d.jsx(Fa.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-10",children:d.jsx(FF,{selectedTool:i,toolArgs:g,isExecuting:w,isConnected:o,onArgChange:Ce,onExecute:He,onSave:ot})},"detail"),$==="response"&&d.jsx(Fa.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-20",children:d.jsx(HF,{results:it,copiedResult:_,previewMode:V,serverId:a,readResource:r,onCopy:st,onDelete:Je,onFullscreen:kt,onTogglePreview:()=>Y(!V)})},"response")]})}),d.jsx(UF,{isOpen:B,requestName:Z,defaultPlaceholder:`${i?.name} - ${new Date().toLocaleString()}`,onRequestNameChange:te,onSave:zn,onCancel:()=>K(!1)})]}):d.jsxs(Ta,{direction:"horizontal",className:"h-full",children:[d.jsx(Yn,{ref:he,defaultSize:33,collapsible:!0,className:"flex flex-col h-full relative",children:d.jsxs(Ta,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[d.jsx(Yn,{defaultSize:75,minSize:30,children:d.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[d.jsx(GF,{activeTab:O,isSearchExpanded:F,searchQuery:A,filteredToolsCount:Ve.length,savedRequestsCount:L.length,onSearchExpand:()=>ae(!0),onSearchChange:C,onSearchBlur:Ee,onTabSwitch:()=>M(O==="tools"?"saved":"tools"),searchInputRef:H}),O==="tools"?d.jsx(VF,{tools:Ve,selectedTool:i,onToolSelect:ct,focusedIndex:ee}):d.jsx($F,{savedRequests:L,selectedRequest:u,onLoadRequest:rt,onDeleteRequest:qt,focusedIndex:ee})]})}),d.jsx(Ho,{withHandle:!0}),d.jsxs(Yn,{ref:$e,defaultSize:0,collapsible:!0,minSize:5,collapsedSize:5,style:{minHeight:45},onCollapse:()=>{J(!0)},onExpand:()=>{J(!1)},className:"flex flex-col border-t dark:border-zinc-700",children:[d.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:Ye=>{Ye.preventDefault(),Ye.stopPropagation(),ne?($e.current?.resize(25),J(!1)):($e.current?.resize(5),J(!0))},children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),pe>0&&d.jsx(Pr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:pe}),pe>0&&!ne&&d.jsx(Me,{variant:"ghost",size:"sm",onClick:Ye=>{Ye.preventDefault(),Ye.stopPropagation(),Ge.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:d.jsx(ni,{className:"h-3.5 w-3.5"})})]}),d.jsx(hs,{className:`h-4 w-4 text-muted-foreground transition-transform ${ne?"":"rotate-180"}`})]}),d.jsx("div",{className:`flex-1 overflow-hidden min-h-0 ${ne?"hidden":""}`,children:d.jsx(KO,{serverIds:[a],onCountChange:me,onClearRef:Ge})})]})]})}),d.jsx(Ho,{withHandle:!0}),d.jsx(Yn,{defaultSize:67,children:d.jsxs(Ta,{direction:"vertical",children:[d.jsx(Yn,{ref:Te,defaultSize:40,collapsible:!0,children:d.jsx(FF,{selectedTool:i,toolArgs:g,isExecuting:w,isConnected:o,onArgChange:Ce,onExecute:He,onSave:ot,onCancel:()=>{k&&k.abort()}})}),d.jsx(Ho,{withHandle:!0}),d.jsx(Yn,{ref:Be,defaultSize:60,children:d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(HF,{results:it,copiedResult:_,previewMode:V,serverId:a,readResource:r,onCopy:st,onDelete:Je,onFullscreen:kt,onTogglePreview:()=>Y(!V),onMaximize:Nn,isMaximized:W})})})]})}),d.jsx(UF,{isOpen:B,requestName:Z,defaultPlaceholder:`${i?.name} - ${new Date().toLocaleString()}`,onRequestNameChange:te,onSave:zn,onCancel:()=>K(!1)})]})}FW.displayName="ToolsTab";function aTe({isSearchExpanded:e,searchQuery:t,filteredRequestsCount:n,requestsCount:r,onSearchExpand:a,onSearchChange:o,onSearchBlur:i,onRejectAll:l,searchInputRef:u}){return d.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[d.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?d.jsx(Hn,{ref:u,placeholder:"Search requests...",value:t,onChange:f=>o(f.target.value),onBlur:i,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Sampling"}),d.jsx(Pr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:d.jsx(sf,{className:"h-4 w-4"})})}),d.jsxs(Yt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(xh,{children:"F"})]})]})]})}),d.jsx("div",{className:"flex items-center gap-2",children:d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:l,disabled:r===0,className:"h-8 w-8 p-0",children:d.jsx(ni,{className:"h-4 w-4"})})}),d.jsx(Yt,{side:"bottom",children:"Reject all"})]})})]})}function oTe({requests:e,selectedRequest:t,onRequestSelect:n,focusedIndex:r,formatRelativeTime:a,listRef:o}){return e.length===0?d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx(of,{vertical:!0,noBorder:!0,message:"No sampling requests"})}):d.jsx("div",{ref:o,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((i,l)=>{const u=i.request.params?.messages?.length||0,f=i.request.params?.maxTokens;return d.jsx(El,{id:`sampling-request-${i.id}`,isSelected:t?.id===i.id,isFocused:r===l,title:d.jsxs("span",{className:"flex items-center gap-3",children:[i.serverName,d.jsx("span",{className:"size-1.5 block rounded-full bg-orange-500"})]}),description:(()=>{const m=a(i.timestamp),h=[];u>0&&h.push(`${u} message${u>1?"s":""}`),f&&h.push(`max ${f} tokens`);const g=h.length>0?` | ${h.join(", ")}`:"";return m+g})(),onClick:()=>n(i)},i.id)})})}function sTe({llmConfig:e}){const t=y.useRef(null);return{generateResponse:y.useCallback(async({request:r})=>{if(!e)throw new Error("LLM config is not available");const a=r.params||{},o=a.maxTokens,i=a.temperature;a.modelPreferences;const l=a.messages||[];if(console.log("[useSamplingLLM] Request structure:",{hasParams:!!a,messagesCount:l.length,messages:l,params:a}),l.length===0)throw new Error("No messages found in sampling request");const u=[],{HumanMessage:f,AIMessage:m}=await Ua(async()=>{const{HumanMessage:E,AIMessage:x}=await import("./index-VN9j3XIi.js").then(w=>w.bK);return{HumanMessage:E,AIMessage:x}},[]);for(const E of l){if(!E||!E.role){console.warn("Skipping invalid message:",E);continue}const x=Array.isArray(E.content)?E.content[0]:E.content;if(!x){console.warn("Skipping message with no content:",E);continue}x.type==="text"&&x.text?E.role==="user"?u.push(new f(x.text)):E.role==="assistant"&&u.push(new m(x.text)):console.warn("Skipping message with unsupported content type:",x)}if(u.length===0)throw new Error("No valid messages could be converted. Please ensure messages have 'text' content type.");if(!t.current||t.current.provider!==e.provider||t.current.model!==e.model||t.current.apiKey!==e.apiKey){let E;const x={model:e.model,apiKey:e.apiKey};if(o!==void 0&&(x.maxTokens=o),i!==void 0?x.temperature=i:e.temperature!==void 0&&(x.temperature=e.temperature),e.provider==="openai"){const{ChatOpenAI:w}=await Ua(async()=>{const{ChatOpenAI:S}=await import("./index-DnfVI-Ze.js");return{ChatOpenAI:S}},__vite__mapDeps([0,1,2,3,4,5]));E=new w(x)}else if(e.provider==="anthropic"){const{ChatAnthropic:w}=await Ua(async()=>{const{ChatAnthropic:S}=await import("./index-BmT6F6tU.js");return{ChatAnthropic:S}},__vite__mapDeps([6,2,1,5]));E=new w(x)}else if(e.provider==="google"){const{ChatGoogleGenerativeAI:w}=await Ua(async()=>{const{ChatGoogleGenerativeAI:S}=await import("./index-DqIRqeuh.js");return{ChatGoogleGenerativeAI:S}},__vite__mapDeps([7,2,1,4]));E=new w(x)}else throw new Error(`Unsupported LLM provider: ${e.provider}`);t.current={instance:E,provider:e.provider,model:e.model,apiKey:e.apiKey}}const h=await t.current.instance.invoke(u);return{role:"assistant",content:{type:"text",text:h.content||h.text||""},model:e.model,stopReason:"endTurn"}},[e]),isAvailable:e!==null}}function iTe({request:e,onApprove:t,onReject:n,onClose:r,previewMode:a,onTogglePreview:o,isCopied:i,onCopy:l,onDownload:u,onFullscreen:f,llmConfig:m}){const[h,g]=y.useState("manual"),[b,E]=y.useState("stub-model"),[x,w]=y.useState("endTurn"),[S,_]=y.useState("assistant"),[T,k]=y.useState("text"),[R,A]=y.useState("positive"),[C,O]=y.useState(""),[M,L]=y.useState("image/png"),[j,B]=y.useState(!1),[K,Z]=y.useState(null),{generateResponse:te,isAvailable:V}=sTe({llmConfig:m});y.useEffect(()=>{e&&(E("stub-model"),w("endTurn"),_("assistant"),k("text"),A("positive"),O(""),L("image/png"),Z(null))},[e?.id]);const Y=async()=>{if(!(!e||!V)){B(!0),Z(null);try{const P=await te({request:e.request});E(P.model||m?.model||"stub-model"),w(P.stopReason||"endTurn"),_(P.role||"assistant");const H=Array.isArray(P.content)?P.content[0]:P.content;H.type==="text"?(k("text"),A(H.text||"")):H.type==="image"&&(k("image"),O(H.data||""),L(H.mimeType||"image/png"))}catch(P){const H=P instanceof Error?P.message:"Failed to generate response";Z(H),At.error("LLM Generation Failed",{description:H})}finally{B(!1)}}},F=y.useMemo(()=>{const P={model:b,stopReason:x,role:S,content:{type:T}};return T==="text"?P.content.text=R:T==="image"&&(P.content.data=C,P.content.mimeType=M),P},[b,x,S,T,R,C,M]),ae=()=>{if(!e)return;const P=fN.safeParse(F);if(!P.success){At.error("Invalid response",{description:`Validation failed: ${P.error.message}`});return}t(e.id,P.data),r(),Ua(()=>Promise.resolve().then(()=>Ec),void 0).then(H=>{const U=At(H.createElement("div",{className:"space-y-3"},H.createElement("div",null,H.createElement("strong",null,"Sampling Response Sent"),H.createElement("p",{className:"text-sm text-muted-foreground mt-1"},"The tool will continue executing.")),H.createElement("div",{className:"flex gap-2"},H.createElement("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>{const D=new globalThis.CustomEvent("navigate-to-tool-result",{detail:{toolName:e.toolName}});window.dispatchEvent(D),At.dismiss(U)}},"View Tool Result"))),{duration:5e3})})},ee=()=>{e&&(n(e.id,"User rejected sampling request"),r())};return e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:"flex items-center justify-between p-4 border-b dark:border-zinc-700",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h3",{className:"font-medium text-gray-900 dark:text-gray-100",children:e.serverName}),d.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleString()})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:l,className:"h-8 w-8 p-0",children:i?d.jsx(Or,{className:"h-4 w-4 text-green-600"}):d.jsx(wr,{className:"h-4 w-4"})})}),d.jsx(Yt,{children:"Copy request"})]}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",children:d.jsx(th,{className:"h-4 w-4"})})}),d.jsx(Yt,{children:"Download request"})]}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:f,className:"h-8 w-8 p-0",children:d.jsx(qN,{className:"h-4 w-4"})})}),d.jsx(Yt,{children:"Fullscreen"})]}),d.jsx(Me,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:d.jsx(vs,{className:"h-4 w-4"})})]})]}),d.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[d.jsxs("div",{className:"space-y-2",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Request"}),d.jsx("div",{className:"bg-muted rounded-lg p-3 max-h-64 overflow-auto",children:d.jsx(yr,{data:e.request})})]}),d.jsxs("div",{className:"space-y-4",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Response"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx(wn,{htmlFor:`responseMode-${e.id}`,className:"text-xs text-gray-500 dark:text-gray-400",children:"Mode:"}),d.jsxs(Zs,{value:h,onValueChange:P=>g(P),children:[d.jsx(Xs,{id:`responseMode-${e.id}`,className:"w-32 h-8 text-xs",children:d.jsx(qs,{})}),d.jsxs(Js,{children:[d.jsx(fa,{value:"manual",children:"Manual"}),d.jsx(fa,{value:"llm",children:"LLM"})]})]})]})]}),h==="llm"&&d.jsxs("div",{className:"space-y-2 p-3 bg-muted rounded-lg",children:[V?d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx(Me,{onClick:Y,disabled:j,size:"sm",className:"flex items-center gap-2",children:j?d.jsxs(d.Fragment,{children:[d.jsx(cl,{className:"h-4 w-4 animate-spin"}),"Generating..."]}):d.jsxs(d.Fragment,{children:[d.jsx(pde,{className:"h-4 w-4"}),"Generate with LLM"]})}),d.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["Using ",m?.provider," (",m?.model,")"]})]}):d.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:"LLM not configured. Please configure LLM in the Chat tab."}),K&&d.jsx("div",{className:"text-xs text-red-600 dark:text-red-400",children:K})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(wn,{htmlFor:`model-${e.id}`,children:"Model"}),d.jsx(Hn,{id:`model-${e.id}`,value:b,onChange:P=>E(P.target.value),placeholder:"stub-model",disabled:h==="llm"&&j})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(wn,{htmlFor:`stopReason-${e.id}`,children:"Stop Reason"}),d.jsx(Hn,{id:`stopReason-${e.id}`,value:x,onChange:P=>w(P.target.value),placeholder:"endTurn",disabled:h==="llm"&&j})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(wn,{htmlFor:`role-${e.id}`,children:"Role"}),d.jsxs(Zs,{value:S,onValueChange:P=>_(P),disabled:h==="llm"&&j,children:[d.jsx(Xs,{id:`role-${e.id}`,children:d.jsx(qs,{})}),d.jsxs(Js,{children:[d.jsx(fa,{value:"assistant",children:"assistant"}),d.jsx(fa,{value:"user",children:"user"})]})]})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(wn,{htmlFor:`contentType-${e.id}`,children:"Content Type"}),d.jsxs(Zs,{value:T,onValueChange:P=>k(P),disabled:h==="llm"&&j,children:[d.jsx(Xs,{id:`contentType-${e.id}`,children:d.jsx(qs,{})}),d.jsxs(Js,{children:[d.jsx(fa,{value:"text",children:"text"}),d.jsx(fa,{value:"image",children:"image"})]})]})]}),T==="text"&&d.jsxs("div",{className:"space-y-2",children:[d.jsx(wn,{htmlFor:`text-${e.id}`,children:"Text Content"}),d.jsx(bc,{id:`text-${e.id}`,value:R,onChange:P=>A(P.target.value),placeholder:"Enter response text...",rows:6,disabled:h==="llm"&&j})]}),T==="image"&&d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"space-y-2",children:[d.jsx(wn,{htmlFor:`imageData-${e.id}`,children:"Base64 Image Data"}),d.jsx(bc,{id:`imageData-${e.id}`,value:C,onChange:P=>O(P.target.value),placeholder:"Base64 encoded image data...",rows:4,disabled:h==="llm"&&j})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(wn,{htmlFor:`mimeType-${e.id}`,children:"MIME Type"}),d.jsx(Hn,{id:`mimeType-${e.id}`,value:M,onChange:P=>L(P.target.value),placeholder:"image/png",disabled:h==="llm"&&j})]})]})]})]}),d.jsxs("div",{className:"flex gap-2 p-4 border-t dark:border-zinc-700",children:[d.jsx(Me,{onClick:ae,className:"flex-1",disabled:h==="llm"&&j,children:"Approve"}),d.jsx(Me,{onClick:ee,variant:"outline",className:"flex-1",disabled:h==="llm"&&j,children:"Reject"})]})]}):d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select a sampling request to view details"})})}const lTe={model:"stub-model",stopReason:"endTurn",role:"assistant",content:{type:"text",text:"positive"}};function cTe({requestId:e,serverName:t,onViewDetails:n,onApprove:r,onDeny:a}){return d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{children:[d.jsx("strong",{children:"Sampling Request Received"}),d.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["New request from ",t]})]}),d.jsxs("div",{className:"flex gap-2",children:[d.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:o=>{o.stopPropagation(),n()},children:"View Details"}),d.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:o=>{o.stopPropagation(),r(lTe)},children:"Approve"}),d.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:o=>{o.stopPropagation(),a()},children:"Deny"})]})]})}function uTe({pendingRequests:e,onApprove:t,onReject:n,serverId:r,isConnected:a,mcpServerUrl:o}){const{selectedSamplingRequestId:i,setSelectedSamplingRequestId:l}=kc(),{llmConfig:u}=mW({mcpServerUrl:o}),[f,m]=y.useState(null),[h,g]=y.useState(""),[b,E]=y.useState(-1),[x,w]=y.useState(!0),[S,_]=y.useState(!1),[T,k]=y.useState(!0),[R,A]=y.useState(!1),C=y.useRef(null),O=y.useRef(null),M=y.useRef(null),L=y.useRef(!1);y.useEffect(()=>{if(console.log("[SamplingTab] Auto-selection check:",{selectedSamplingRequestId:i,pendingRequestsCount:e.length,currentSelectedId:f?.id}),i&&e.length>0){const F=e.find(ae=>ae.id===i);console.log("[SamplingTab] Found request for auto-selection:",!!F,F?.id),F&&(console.log("[SamplingTab] Auto-selecting request:",F.id),l(null),m(F),setTimeout(()=>{const ae=document.getElementById(`sampling-request-${F.id}`);console.log("[SamplingTab] Scrolling to element:",!!ae),ae&&ae.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[i,e,l]),y.useEffect(()=>{const F=ae=>{const P=ae.detail.requestId;console.log("[SamplingTab] Custom navigate event received:",P);const H=e.find(U=>U.id===P);H&&(console.log("[SamplingTab] Selecting request from event:",P),m(H),setTimeout(()=>{const U=document.getElementById(`sampling-request-${P}`);U&&U.scrollIntoView({behavior:"smooth",block:"nearest"})},200))};return window.addEventListener("navigate-to-sampling",F),()=>window.removeEventListener("navigate-to-sampling",F)},[e]),y.useEffect(()=>{x&&e.length>0&&C.current&&!L.current&&(C.current.scrollTop=0)},[e.length,x]),y.useEffect(()=>{const F=C.current;if(!F)return;const ae=()=>{F.scrollTop>0&&(L.current=!0,w(!1))};return F.addEventListener("scroll",ae),()=>F.removeEventListener("scroll",ae)},[]),y.useEffect(()=>{e.length===0&&(L.current=!1,w(!0))},[e.length]),y.useEffect(()=>{S&&M.current&&M.current.focus()},[S]);const j=y.useCallback(()=>{h.trim()||_(!1)},[h]),B=y.useMemo(()=>{if(!h.trim())return e;const F=h.toLowerCase();return e.filter(ae=>ae.serverName.toLowerCase().includes(F)||JSON.stringify(ae.request||{}).toLowerCase().includes(F))},[e,h]);y.useEffect(()=>{E(-1)},[h]),y.useEffect(()=>{const F=ae=>{const ee=ae.target;if(ee.tagName==="INPUT"||ee.tagName==="TEXTAREA"||ee.contentEditable==="true"||ae.metaKey||ae.ctrlKey||ae.altKey)return;const H=B;if(ae.key==="ArrowDown")ae.preventDefault(),E(U=>{const D=U+1;return D>=H.length?0:D});else if(ae.key==="ArrowUp")ae.preventDefault(),E(U=>{const D=U-1;return D<0?H.length-1:D});else if(ae.key==="Enter"&&b>=0){ae.preventDefault();const U=B[b];U&&K(U)}};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[b,B]),y.useEffect(()=>{if(b>=0){const F=`sampling-request-${B[b]?.id}`,ae=document.getElementById(F);ae&&ae.scrollIntoView({behavior:"smooth",block:"nearest"})}},[b,B]);const K=y.useCallback(F=>{m(F)},[]),Z=y.useCallback(()=>{window.confirm("Are you sure you want to reject all sampling requests? This cannot be undone.")&&(e.forEach(F=>{n(F.id,"User rejected all requests")}),m(null))},[e,n]),te=y.useCallback(async()=>{if(f)try{await navigator.clipboard.writeText(JSON.stringify({id:f.id,serverName:f.serverName,timestamp:f.timestamp,request:f.request},null,2)),A(!0),setTimeout(()=>A(!1),2e3)}catch(F){console.error("[SamplingTab] Failed to copy request:",F)}},[f]),V=y.useCallback(()=>{if(f)try{const F=new globalThis.Blob([JSON.stringify({id:f.id,serverName:f.serverName,timestamp:f.timestamp,request:f.request},null,2)],{type:"application/json"}),ae=URL.createObjectURL(F),ee=document.createElement("a");ee.href=ae,ee.download=`sampling-request-${Date.now()}.json`,document.body.appendChild(ee),ee.click(),document.body.removeChild(ee),URL.revokeObjectURL(ae)}catch(F){console.error("[SamplingTab] Failed to download request:",F)}},[f]),Y=y.useCallback(async()=>{if(O.current)try{document.fullscreenElement?await document.exitFullscreen():await O.current.requestFullscreen()}catch(F){console.error("[SamplingTab] Failed to toggle fullscreen:",F)}},[]);return a?d.jsxs(Ta,{direction:"horizontal",className:"h-full",children:[d.jsx(Yn,{defaultSize:40,minSize:30,children:d.jsx(Ta,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:d.jsxs(Yn,{defaultSize:75,minSize:30,children:[d.jsx(aTe,{isSearchExpanded:S,searchQuery:h,filteredRequestsCount:B.length,requestsCount:e.length,onSearchExpand:()=>_(!0),onSearchChange:g,onSearchBlur:j,onRejectAll:Z,searchInputRef:M}),d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(oTe,{requests:B,selectedRequest:f,onRequestSelect:K,focusedIndex:b,formatRelativeTime:Ev,listRef:C})})]})})}),d.jsx(Ho,{}),d.jsx(Yn,{defaultSize:60,minSize:40,children:d.jsx("div",{ref:O,className:"h-full bg-white dark:bg-zinc-900",children:d.jsx(iTe,{request:f,onApprove:t,onReject:n,onClose:()=>m(null),previewMode:T,onTogglePreview:()=>k(!T),isCopied:R,onCopy:te,onDownload:V,onFullscreen:Y,llmConfig:u})})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(BH,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function dTe({isSearchExpanded:e,searchQuery:t,filteredRequestsCount:n,requestsCount:r,onSearchExpand:a,onSearchChange:o,onSearchBlur:i,onCancelAll:l,searchInputRef:u}){return d.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[d.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?d.jsx(Hn,{ref:u,placeholder:"Search requests...",value:t,onChange:f=>o(f.target.value),onBlur:i,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Elicitation"}),d.jsx(Pr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:d.jsx(sf,{className:"h-4 w-4"})})}),d.jsxs(Yt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(xh,{children:"F"})]})]})]})}),d.jsx("div",{className:"flex items-center gap-2",children:d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:l,disabled:r===0,className:"h-8 w-8 p-0",children:d.jsx(vs,{className:"h-4 w-4"})})}),d.jsx(Yt,{side:"bottom",children:"Cancel all"})]})})]})}function fTe({requests:e,selectedRequest:t,onRequestSelect:n,focusedIndex:r,formatRelativeTime:a,listRef:o}){return e.length===0?d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx(of,{vertical:!0,noBorder:!0,message:"No elicitation requests"})}):d.jsx("div",{ref:o,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((i,l)=>{const u=i.request.mode||"form",f=u==="form"&&"requestedSchema"in i.request&&i.request.requestedSchema;return d.jsx(El,{id:`elicitation-request-${i.id}`,isSelected:t?.id===i.id,isFocused:r===l,title:d.jsxs("span",{className:"flex items-center gap-3",children:[i.serverName,d.jsx(Pr,{variant:"outline",className:u==="url"?"bg-blue-500/20 text-blue-600 dark:text-blue-400 border-blue-500/50":"bg-green-500/20 text-green-600 dark:text-green-400 border-green-500/50",children:u})]}),description:(()=>{const m=a(i.timestamp),h=[];f&&h.push("with schema"),u==="url"&&h.push("external action");const g=h.length>0?` | ${h.join(", ")}`:"";return m+g})(),onClick:()=>n(i)},i.id)})})}function pTe({request:e,onApprove:t,onReject:n,onClose:r,previewMode:a,onTogglePreview:o,isCopied:i,onCopy:l,onDownload:u,onFullscreen:f}){const[m,h]=y.useState({}),[g,b]=y.useState(!1),E=e?.request.mode||"form",x=E==="form",w=E==="url";y.useEffect(()=>{if(e&&x&&"requestedSchema"in e.request){const C=e.request.requestedSchema,O={};if(C?.type==="object"&&C.properties)for(const[M,L]of Object.entries(C.properties)){const j=L;j.default!==void 0?O[M]=j.default:j.type==="boolean"?O[M]=!1:j.type==="number"||j.type==="integer"?O[M]=0:O[M]=""}h(O)}b(!1)},[e?.id,x]);const S=(C,O)=>{h(M=>({...M,[C]:O}))},_=()=>{if(e){if(x){if("requestedSchema"in e.request){const C=e.request.requestedSchema;if(C?.required){const O=C.required.filter(M=>m[M]===void 0||m[M]===""||m[M]===null);if(O.length>0){At.error("Missing required fields",{description:`Please fill in: ${O.join(", ")}`});return}}}t(e.id,{action:"accept",data:m})}else w&&t(e.id,{action:"accept"});r(),Ua(()=>Promise.resolve().then(()=>Ec),void 0).then(C=>{const O=At(C.createElement("div",{className:"space-y-3"},C.createElement("div",null,C.createElement("strong",null,"Elicitation Response Sent"),C.createElement("p",{className:"text-sm text-muted-foreground mt-1"},"The tool will continue executing.")),C.createElement("div",{className:"flex gap-2"},C.createElement("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>{const M=new globalThis.CustomEvent("navigate-to-tool-result",{detail:{toolName:null}});window.dispatchEvent(M),At.dismiss(O)}},"View Tool Result"))),{duration:5e3})})}},T=()=>{e&&(t(e.id,{action:"decline"}),r())},k=()=>{e&&(n(e.id,"User cancelled elicitation request"),r())},R=()=>{e&&w&&"url"in e.request&&(window.open(e.request.url,"_blank"),b(!0))},A=y.useMemo(()=>{if(!e||!x||!("requestedSchema"in e.request))return null;const C=e.request.requestedSchema;if(!C||C.type!=="object"||!C.properties)return d.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"No form schema available"});const O=C.properties,M=C.required||[];return d.jsx("div",{className:"space-y-4",children:Object.entries(O).map(([L,j])=>{const B=j,K=M.includes(L),Z=B.type||"string",te=B.title||L,V=B.description;return d.jsxs("div",{className:"space-y-2",children:[d.jsxs(wn,{htmlFor:`field-${L}`,children:[te,K&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),V&&d.jsx("p",{className:"text-xs text-muted-foreground",children:V}),Z==="boolean"?d.jsxs("div",{className:"flex items-center space-x-2",children:[d.jsx(Mm,{id:`field-${L}`,checked:m[L]||!1,onCheckedChange:Y=>S(L,Y)}),d.jsx(wn,{htmlFor:`field-${L}`,className:"text-sm font-normal cursor-pointer",children:B.title||L})]}):Z==="number"||Z==="integer"?d.jsx(Hn,{id:`field-${L}`,type:"number",value:m[L]||"",onChange:Y=>S(L,Z==="integer"?parseInt(Y.target.value,10):parseFloat(Y.target.value)),placeholder:B.default?.toString()||""}):B.enum?d.jsxs("select",{id:`field-${L}`,value:m[L]||"",onChange:Y=>S(L,Y.target.value),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:[d.jsx("option",{value:"",children:"Select..."}),B.enum.map(Y=>d.jsx("option",{value:Y,children:Y},Y))]}):Z==="string"&&(B.format==="textarea"||B.maxLength>100)?d.jsx(bc,{id:`field-${L}`,value:m[L]||"",onChange:Y=>S(L,Y.target.value),placeholder:B.default||"",rows:4}):d.jsx(Hn,{id:`field-${L}`,type:"text",value:m[L]||"",onChange:Y=>S(L,Y.target.value),placeholder:B.default||""})]},L)})})},[e,m,x]);return e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:"flex items-center justify-between p-4 border-b dark:border-zinc-700",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h3",{className:"font-medium text-gray-900 dark:text-gray-100",children:e.serverName}),d.jsx(Pr,{variant:"outline",className:w?"bg-blue-500/20 text-blue-600 dark:text-blue-400 border-blue-500/50":"bg-green-500/20 text-green-600 dark:text-green-400 border-green-500/50",children:E}),d.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleString()})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:l,className:"h-8 w-8 p-0",children:i?d.jsx(Or,{className:"h-4 w-4 text-green-600"}):d.jsx(wr,{className:"h-4 w-4"})})}),d.jsx(Yt,{children:"Copy request"})]}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",children:d.jsx(th,{className:"h-4 w-4"})})}),d.jsx(Yt,{children:"Download request"})]}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:f,className:"h-8 w-8 p-0",children:d.jsx(qN,{className:"h-4 w-4"})})}),d.jsx(Yt,{children:"Fullscreen"})]}),d.jsx(Me,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:d.jsx(vs,{className:"h-4 w-4"})})]})]}),d.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[d.jsxs("div",{className:"space-y-2",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Message"}),d.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:e.request.message})]}),w&&"url"in e.request&&d.jsxs("div",{className:"space-y-2",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"External Action Required"}),d.jsxs("div",{className:"bg-muted rounded-lg p-4 space-y-3",children:[d.jsx("p",{className:"text-sm text-muted-foreground",children:"This request requires you to complete an action at an external URL:"}),d.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background rounded border",children:[d.jsx("code",{className:"flex-1 text-xs font-mono break-all",children:e.request.url}),d.jsxs(Me,{size:"sm",variant:"outline",onClick:R,className:"flex items-center gap-2",children:[d.jsx(u_,{className:"h-4 w-4"}),"Open URL"]})]}),d.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[d.jsx(Mm,{id:"url-completed",checked:g,onCheckedChange:C=>b(!!C)}),d.jsx(wn,{htmlFor:"url-completed",className:"text-sm font-normal cursor-pointer",children:"I have completed the required action"})]})]})]}),x&&d.jsxs("div",{className:"space-y-2",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Form Data"}),A]}),x&&"requestedSchema"in e.request&&e.request.requestedSchema&&d.jsxs("details",{className:"space-y-2",children:[d.jsx("summary",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100 cursor-pointer",children:"Schema (for reference)"}),d.jsx("div",{className:"bg-muted rounded-lg p-3 max-h-64 overflow-auto",children:d.jsx(yr,{data:e.request.requestedSchema})})]})]}),d.jsxs("div",{className:"flex gap-2 p-4 border-t dark:border-zinc-700",children:[d.jsx(Me,{onClick:_,className:"flex-1",children:"Accept"}),d.jsx(Me,{onClick:T,variant:"outline",className:"flex-1",children:"Decline"}),d.jsx(Me,{onClick:k,variant:"outline",className:"flex-1",children:"Cancel"})]})]}):d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select an elicitation request to view details"})})}function mTe({pendingRequests:e=[],onApprove:t,onReject:n,serverId:r,isConnected:a}){const{selectedElicitationRequestId:o,setSelectedElicitationRequestId:i}=kc(),[l,u]=y.useState(null),[f,m]=y.useState(""),[h,g]=y.useState(-1),[b,E]=y.useState(!0),[x,w]=y.useState(!1),[S,_]=y.useState(!0),[T,k]=y.useState(!1),R=y.useRef(null),A=y.useRef(null),C=y.useRef(null),O=y.useRef(!1);y.useEffect(()=>{if(console.log("[ElicitationTab] Auto-selection check:",{selectedElicitationRequestId:o,pendingRequestsCount:e.length,currentSelectedId:l?.id}),o&&e.length>0){const V=e.find(Y=>Y.id===o);console.log("[ElicitationTab] Found request for auto-selection:",!!V,V?.id),V&&(console.log("[ElicitationTab] Auto-selecting request:",V.id),i(null),u(V),setTimeout(()=>{const Y=document.getElementById(`elicitation-request-${V.id}`);console.log("[ElicitationTab] Scrolling to element:",!!Y),Y&&Y.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[o,e,i]),y.useEffect(()=>{const V=Y=>{const ae=Y.detail.requestId;console.log("[ElicitationTab] Custom navigate event received:",ae);const ee=e.find(P=>P.id===ae);ee&&(console.log("[ElicitationTab] Selecting request from event:",ae),u(ee),setTimeout(()=>{const P=document.getElementById(`elicitation-request-${ae}`);P&&P.scrollIntoView({behavior:"smooth",block:"nearest"})},200))};return window.addEventListener("navigate-to-elicitation",V),()=>window.removeEventListener("navigate-to-elicitation",V)},[e]),y.useEffect(()=>{b&&e.length>0&&R.current&&!O.current&&(R.current.scrollTop=0)},[e.length,b]),y.useEffect(()=>{const V=R.current;if(!V)return;const Y=()=>{V.scrollTop>0&&(O.current=!0,E(!1))};return V.addEventListener("scroll",Y),()=>V.removeEventListener("scroll",Y)},[]),y.useEffect(()=>{e.length===0&&(O.current=!1,E(!0))},[e.length]),y.useEffect(()=>{x&&C.current&&C.current.focus()},[x]);const M=y.useCallback(()=>{f.trim()||w(!1)},[f]),L=y.useMemo(()=>{if(!f.trim())return e;const V=f.toLowerCase();return e.filter(Y=>Y.serverName.toLowerCase().includes(V)||Y.request.message.toLowerCase().includes(V)||JSON.stringify(Y.request||{}).toLowerCase().includes(V))},[e,f]);y.useEffect(()=>{g(-1)},[f]),y.useEffect(()=>{const V=Y=>{const F=Y.target;if(F.tagName==="INPUT"||F.tagName==="TEXTAREA"||F.contentEditable==="true"||Y.metaKey||Y.ctrlKey||Y.altKey)return;const ee=L;if(Y.key==="ArrowDown")Y.preventDefault(),g(P=>{const H=P+1;return H>=ee.length?0:H});else if(Y.key==="ArrowUp")Y.preventDefault(),g(P=>{const H=P-1;return H<0?ee.length-1:H});else if(Y.key==="Enter"&&h>=0){Y.preventDefault();const P=L[h];P&&j(P)}};return document.addEventListener("keydown",V),()=>document.removeEventListener("keydown",V)},[h,L]),y.useEffect(()=>{if(h>=0){const V=`elicitation-request-${L[h]?.id}`,Y=document.getElementById(V);Y&&Y.scrollIntoView({behavior:"smooth",block:"nearest"})}},[h,L]);const j=y.useCallback(V=>{u(V)},[]),B=y.useCallback(()=>{window.confirm("Are you sure you want to cancel all elicitation requests? This cannot be undone.")&&(e.forEach(V=>{n(V.id,"User cancelled all requests")}),u(null))},[e,n]),K=y.useCallback(async()=>{if(l)try{await navigator.clipboard.writeText(JSON.stringify({id:l.id,serverName:l.serverName,timestamp:l.timestamp,request:l.request},null,2)),k(!0),setTimeout(()=>k(!1),2e3)}catch(V){console.error("[ElicitationTab] Failed to copy request:",V)}},[l]),Z=y.useCallback(()=>{if(l)try{const V=new globalThis.Blob([JSON.stringify({id:l.id,serverName:l.serverName,timestamp:l.timestamp,request:l.request},null,2)],{type:"application/json"}),Y=URL.createObjectURL(V),F=document.createElement("a");F.href=Y,F.download=`elicitation-request-${Date.now()}.json`,document.body.appendChild(F),F.click(),document.body.removeChild(F),URL.revokeObjectURL(Y)}catch(V){console.error("[ElicitationTab] Failed to download request:",V)}},[l]),te=y.useCallback(async()=>{if(A.current)try{document.fullscreenElement?await document.exitFullscreen():await A.current.requestFullscreen()}catch(V){console.error("[ElicitationTab] Failed to toggle fullscreen:",V)}},[]);return a?d.jsxs(Ta,{direction:"horizontal",className:"h-full",children:[d.jsx(Yn,{defaultSize:40,minSize:30,children:d.jsx(Ta,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:d.jsxs(Yn,{defaultSize:75,minSize:30,children:[d.jsx(dTe,{isSearchExpanded:x,searchQuery:f,filteredRequestsCount:L.length,requestsCount:e.length,onSearchExpand:()=>w(!0),onSearchChange:m,onSearchBlur:M,onCancelAll:B,searchInputRef:C}),d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(fTe,{requests:L,selectedRequest:l,onRequestSelect:j,focusedIndex:h,formatRelativeTime:Ev,listRef:R})})]})})}),d.jsx(Ho,{}),d.jsx(Yn,{defaultSize:60,minSize:40,children:d.jsx("div",{ref:A,className:"h-full bg-white dark:bg-zinc-900",children:d.jsx(pTe,{request:l,onApprove:t,onReject:n,onClose:()=>u(null),previewMode:S,onTogglePreview:()=>_(!S),isCopied:T,onCopy:K,onDownload:Z,onFullscreen:te})})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(KH,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function hTe({selectedServer:e,activeTab:t,toolsSearchRef:n,promptsSearchRef:r,resourcesSearchRef:a,children:o}){return e?d.jsxs(d.Fragment,{children:[d.jsx("div",{style:{display:t==="tools"?"block":"none"},className:"h-full",children:d.jsx(FW,{ref:n,tools:e.tools,callTool:e.callTool,readResource:e.readResource,serverId:e.id,isConnected:e.state==="ready"})}),d.jsx("div",{style:{display:t==="prompts"?"block":"none"},className:"h-full",children:d.jsx(PW,{ref:r,prompts:e.prompts,callPrompt:e.getPrompt,serverId:e.id,isConnected:e.state==="ready"})}),d.jsx("div",{style:{display:t==="resources"?"block":"none"},className:"h-full",children:d.jsx(UW,{ref:a,resources:e.resources,readResource:e.readResource,serverId:e.id,isConnected:e.state==="ready"})}),d.jsx("div",{style:{display:t==="chat"?"block":"none"},className:"h-full",children:d.jsx(u_e,{connection:e,isConnected:e.state==="ready",readResource:e.readResource},e.id)}),d.jsx("div",{style:{display:t==="sampling"?"block":"none"},className:"h-full",children:d.jsx(uTe,{pendingRequests:e.pendingSamplingRequests,onApprove:e.approveSampling,onReject:e.rejectSampling,serverId:e.id,isConnected:e.state==="ready",mcpServerUrl:e.url})}),d.jsx("div",{style:{display:t==="elicitation"?"block":"none"},className:"h-full",children:d.jsx(mTe,{pendingRequests:e.pendingElicitationRequests,onApprove:e.approveElicitation,onReject:e.rejectElicitation,serverId:e.id,isConnected:e.state==="ready"})}),d.jsx("div",{style:{display:t==="notifications"?"block":"none"},className:"h-full",children:d.jsx(B_e,{notifications:e.notifications,unreadCount:e.unreadNotificationCount,markNotificationRead:e.markNotificationRead,markAllNotificationsRead:e.markAllNotificationsRead,clearNotifications:e.clearNotifications,serverId:e.id,isConnected:e.state==="ready"})}),t!=="tools"&&t!=="prompts"&&t!=="resources"&&t!=="chat"&&t!=="sampling"&&t!=="elicitation"&&t!=="notifications"&&d.jsx(d.Fragment,{children:o})]}):d.jsx(d.Fragment,{children:o})}function KF({className:e}){return d.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentcolor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[d.jsx("path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"}),d.jsx("path",{d:"M9 18c-4.51 2-5-2-7-2"})]})}const BW=y.createContext(void 0);function HW(){const e=y.use(BW);if(!e)throw new Error("useTabs must be used within a TabsProvider");return e}const VW=y.createContext(void 0);function gTe(){return y.use(VW)}function $T({ref:e,children:t,defaultValue:n,value:r,onValueChange:a,className:o,collapsed:i,onCollapsedChange:l,...u}){const[f,m]=y.useState(n||""),h=r!==void 0,g=i!==void 0,[b,E]=y.useState(!1),x=y.useCallback(T=>{h||m(T),a?.(T)},[h,a]),w=h?r:f,S=g?i:b,_=y.useCallback(T=>{g||E(T),l?.(T)},[g,l]);return d.jsx(BW,{value:{activeValue:w,handleValueChange:x,collapsed:S,handleCollapsedChange:_},children:d.jsx("div",{ref:e,className:Ue("flex flex-col gap-2",o),...u,children:t})})}$T.displayName="Tabs";function UT({ref:e,children:t,className:n,variant:r="default",collapsible:a=!1,...o}){const{activeValue:i,collapsed:l,handleCollapsedChange:u}=HW(),[f,m]=y.useState({width:0,left:0}),h=y.useRef(null),g=y.useRef(null),b=y.useRef(null),E=y.useCallback(()=>{const S=h.current;if(!S)return;const _=S.querySelector("div:first-child");if(!_)return;const T=_.querySelector(`button[data-tab-value="${i}"]`);if(T&&i){const k=_.getBoundingClientRect(),R=T.getBoundingClientRect();m({width:R.width,left:R.left-k.left})}else m({width:0,left:0})},[i]),x=y.useCallback(()=>{b.current&&clearTimeout(b.current),b.current=setTimeout(E,16)},[E]);y.useEffect(()=>{const S=setTimeout(E,10);return()=>clearTimeout(S)},[E,l]),y.useEffect(()=>{const S=h.current;if(!S)return;g.current=new ResizeObserver(()=>{x()}),g.current.observe(S);const _=S.querySelector("div:first-child");return _&&_.querySelectorAll("button[data-tab-value]").forEach(k=>{g.current&&g.current.observe(k)}),()=>{g.current&&g.current.disconnect(),b.current&&clearTimeout(b.current)}},[x]),y.useEffect(()=>{const S=()=>{x()};return window.addEventListener("resize",S),()=>window.removeEventListener("resize",S)},[x]);const w=y.useRef(null);return y.useEffect(()=>{w.current&&(w.current.style.width=`${f.width}px`,w.current.style.left=`${f.left}px`)},[f]),d.jsx(VW,{value:{variant:r,collapsed:l,handleCollapsedChange:u},children:d.jsx("div",{ref:h,className:Ue("relative flex items-center bg-none gap-1",r==="default"&&"p-1 rounded-full border border-zinc-300 dark:border-zinc-600",r==="underline"&&"border-b border-zinc-200 dark:border-zinc-700",n),...o,children:d.jsxs("div",{role:"tablist",className:"flex-1 flex items-center relative",children:[t,d.jsx("span",{ref:w,className:Ue("absolute transition-all duration-500 ease-in-out z-0",r==="default"&&"bg-white dark:bg-zinc-700 rounded-full h-[calc(100%)] top-0 border border-zinc-300 dark:border-zinc-600",r==="underline"&&"bottom-0 h-0.5 bg-black dark:bg-white")})]})})})}UT.displayName="TabsList";const bTe=({children:e,title:t,collapsed:n})=>!t||!n?e:d.jsx(WN,{children:d.jsxs(Wt,{children:[d.jsx(Kt,{children:e}),d.jsx(Yt,{children:t})]})}),zT=y.forwardRef(({children:e,value:t,className:n,disabled:r,icon:a,title:o,showDot:i=!1,...l},u)=>{const{activeValue:f,handleValueChange:m,collapsed:h}=HW(),b=gTe()?.variant||"default",E=f===t,x=h&&o?o:void 0;return d.jsx(bTe,{title:o,collapsed:h,children:d.jsxs("button",{ref:u,disabled:r,onClick:()=>m(t),"data-tab-value":t,"data-tab-active":E,role:"tab","aria-selected":E?"true":"false",title:x,className:Ue("relative z-10 flex-1 inline-flex items-center justify-center whitespace-nowrap text-sm font-medium ring-offset-background transition-all duration-500 ease-in-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 cursor-pointer",b==="default"&&"py-2.5",b==="default"&&"rounded-md px-4",b==="underline"&&"px-6 py-3 border-b-2 border-transparent",E&&"text-foreground",!E&&"text-muted-foreground hover:text-foreground",n),...l,children:[a&&d.jsx(a,{className:Ue("h-4 w-4 transition-all duration-500 ease-in-out",!h&&"mr-2",h&&"mr-0!")}),i&&d.jsx("span",{className:"absolute top-1.5 right-1.5 w-2 h-2 bg-orange-500 dark:bg-orange-400 border-2 border-white dark:border-zinc-900 rounded-full transition-opacity duration-300 z-10 animate-status-pulse-orange"}),d.jsx("span",{className:Ue("transition-all duration-500 ease-in-out overflow-hidden",h?"w-0 opacity-0":"w-auto opacity-100"),children:e})]})})});zT.displayName="TabsTrigger";function YF({serverConfig:e,additionalItems:t=[],showClients:n={cursor:!0,vsCode:!0,claudeDesktop:!0,claudeCode:!0,geminiCli:!0,codexCli:!0},className:r="",onSuccess:a,onError:o,trigger:i}){const[l,u]=y.useState(!1),[f,m]=y.useState(null),[h,g]=y.useState(!1),{url:b,name:E,headers:x}=e,w=()=>{try{const L=jG(b,E,x);window.location.href=L,a?.("Cursor")}catch(L){console.error("Failed to generate Cursor deep link:",L),o?.(L)}},S=()=>{try{const L=PG(b,E,x);window.location.href=L,a?.("VS Code")}catch(L){console.error("Failed to generate VS Code deep link:",L),o?.(L)}},_=()=>{try{$G(b,E,x),a?.("Claude Desktop")}catch(L){console.error("Failed to download .mcpb file:",L),o?.(L)}},T=()=>{m("claude-code"),u(!0)},k=()=>{m("gemini-cli"),u(!0)},R=()=>{m("codex-cli"),u(!0)},A=async L=>{try{await navigator.clipboard.writeText(L),g(!0),setTimeout(()=>g(!1),2e3)}catch(j){console.error("Failed to copy:",j),o?.(j)}},C=()=>{if(f==="claude-code"){const{command:L,envVars:j}=UG(b,E,x),B=P2(j);return d.jsxs(d.Fragment,{children:[d.jsxs(ls,{children:[d.jsx(cs,{children:"Add to Claude Code"}),d.jsx(Fp,{children:"Execute the following command in your shell to add this server to Claude Code."})]}),d.jsxs("div",{className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Instructions"}),d.jsxs("ol",{className:"space-y-2 text-xs text-muted-foreground",children:[d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"1."}),d.jsx("span",{children:"Ensure the Claude Code executable is available in your path"})]}),d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"2."}),d.jsx("span",{children:"Execute the following snippet in your shell:"})]})]})]}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"absolute top-2 right-2 z-10",children:d.jsx(Me,{variant:"ghost",size:"sm",className:"h-7 px-2 bg-background hover:bg-accent border border-border",onClick:()=>A(L),children:h?d.jsx(Or,{className:"size-3.5 text-green-600"}):d.jsx(wr,{className:"size-3.5"})})}),d.jsx("pre",{className:"bg-muted p-3 pr-14 rounded-md text-xs overflow-x-auto",children:d.jsx("code",{children:L})})]}),B&&d.jsxs("div",{children:[d.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Environment Variables"}),d.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"After installation, set these environment variables in your shell:"}),d.jsx("pre",{className:"bg-muted p-3 rounded-md text-xs overflow-x-auto",children:d.jsx("code",{children:B})})]}),d.jsxs("p",{className:"text-xs text-muted-foreground",children:["The MCP configuration supports environment variable expansion using ",d.jsx("code",{className:"text-foreground",children:"${VAR}"})," ","syntax."]})]})]})}if(f==="gemini-cli"){const{command:L,envVars:j}=zG(b,E,x),B=P2(j);return d.jsxs(d.Fragment,{children:[d.jsxs(ls,{children:[d.jsx(cs,{children:"Add to Gemini CLI"}),d.jsx(Fp,{children:"Execute the following command in your shell to add this server to Gemini CLI."})]}),d.jsxs("div",{className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Instructions"}),d.jsxs("ol",{className:"space-y-2 text-xs text-muted-foreground",children:[d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"1."}),d.jsx("span",{children:"Ensure the Gemini CLI executable is available in your path"})]}),B&&d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"2."}),d.jsx("span",{children:"Set these environment variables in your shell before running the command:"})]}),d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:B?"3.":"2."}),d.jsx("span",{children:"Execute the following snippet in your shell:"})]})]})]}),B&&d.jsxs("div",{children:[d.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Environment Variables"}),d.jsx("pre",{className:"bg-muted p-3 rounded-md text-xs overflow-x-auto",children:d.jsx("code",{children:B})})]}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"absolute top-2 right-2 z-10",children:d.jsx(Me,{variant:"ghost",size:"sm",className:"h-7 px-2 bg-background hover:bg-accent border border-border",onClick:()=>A(L),children:h?d.jsx(Or,{className:"size-3.5 text-green-600"}):d.jsx(wr,{className:"size-3.5"})})}),d.jsx("pre",{className:"bg-muted p-3 pr-14 rounded-md text-xs overflow-x-auto",children:d.jsx("code",{children:L})})]}),d.jsx("p",{className:"text-xs text-muted-foreground",children:"Restart Gemini CLI to load the new configuration."})]})]})}if(f==="codex-cli"){const{config:L,envVars:j}=FG(b,E,x);return d.jsxs(d.Fragment,{children:[d.jsxs(ls,{children:[d.jsx(cs,{children:"Add to Codex CLI"}),d.jsxs(Fp,{children:["Add this configuration to your"," ",d.jsx("code",{className:"text-foreground",children:"~/.codex/config.toml"})," ","file."]})]}),d.jsxs("div",{className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Instructions"}),d.jsxs("p",{className:"text-xs text-muted-foreground",children:["Add this configuration to your"," ",d.jsx("code",{className:"text-foreground",children:"~/.codex/config.toml"}),":"]})]}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"absolute top-2 right-2 z-10",children:d.jsx(Me,{variant:"ghost",size:"sm",className:"h-7 px-2 bg-background hover:bg-accent border border-border",onClick:()=>A(L),children:h?d.jsx(Or,{className:"size-3.5 text-green-600"}):d.jsx(wr,{className:"size-3.5"})})}),d.jsx("pre",{className:"bg-muted p-3 pr-14 rounded-md text-xs overflow-x-auto",children:d.jsx("code",{children:L})})]}),j.length>0&&d.jsx("div",{children:d.jsxs("p",{className:"text-xs text-muted-foreground",children:["(optional) If you would rather use variables from your system's environment, replace the"," ",d.jsx("code",{className:"text-foreground",children:"http_headers"})," key with the ",d.jsx("code",{className:"text-foreground",children:"env_http_headers"})," ","key as shown in the commented section above."]})}),d.jsx("p",{className:"text-xs text-muted-foreground",children:"Restart Codex CLI to load the new configuration."})]})]})}return null},O=d.jsxs(Me,{variant:"ghost",className:`bg-zinc-200 dark:bg-zinc-800 hover:bg-zinc-300 dark:hover:bg-zinc-700 rounded-full transition-colors px-3 flex items-center justify-center ${r}`,children:[d.jsxs("span",{className:"xl:hidden hidden sm:flex items-center gap-1",children:[d.jsx(mm,{className:"size-3"}),"Client"]}),d.jsxs("span",{className:"hidden xl:flex items-center gap-1",children:["Add to Client",d.jsx(hs,{className:"size-3"})]})]}),M=i?typeof i=="function"?i({isOpen:!1,onClick:()=>{}}):i:O;return d.jsxs(d.Fragment,{children:[d.jsxs(im,{children:[d.jsx(lm,{asChild:!0,children:M}),d.jsxs(jd,{align:"end",className:"w-auto min-w-[300px]",children:[t.map(L=>d.jsxs(Jr,{onClick:async()=>{await L.onClick()},className:"flex items-center gap-2",children:[L.icon,d.jsx("span",{className:"min-w-0 max-w-full whitespace-nowrap",children:L.label})]},L.id)),t.length>0&&d.jsx(Lu,{}),n.cursor&&d.jsxs(Jr,{onClick:w,className:"flex items-center gap-2",children:[d.jsx("img",{src:"https://cdn.simpleicons.org/cursor",alt:"Cursor",className:"h-4 w-4"}),d.jsx("span",{className:"min-w-0 max-w-full whitespace-nowrap",children:"Cursor"})]}),n.claudeCode&&d.jsxs(Jr,{onClick:T,className:"flex items-center gap-2",children:[d.jsx("img",{src:"https://cdn.simpleicons.org/claude",alt:"Claude",className:"h-4 w-4"}),d.jsx("span",{className:"min-w-0 max-w-full whitespace-nowrap",children:"Claude Code"})]}),n.claudeDesktop&&d.jsxs(Jr,{onClick:_,className:"flex items-center gap-2",children:[d.jsx("img",{src:"https://cdn.simpleicons.org/claude",alt:"Claude",className:"h-4 w-4"}),d.jsx("span",{className:"min-w-0 max-w-full whitespace-nowrap",children:"Claude Desktop"})]}),n.vsCode&&d.jsxs(Jr,{onClick:S,className:"flex items-center gap-2",children:[d.jsx(MG,{className:"h-4 w-4"}),d.jsx("span",{className:"min-w-0 max-w-full whitespace-nowrap",children:"VS Code"})]}),n.geminiCli&&d.jsxs(Jr,{onClick:k,className:"flex items-center gap-2",children:[d.jsx("img",{src:"https://cdn.simpleicons.org/googlegemini",alt:"Gemini",className:"h-4 w-4"}),d.jsx("span",{className:"min-w-0 max-w-full whitespace-nowrap",children:"Gemini CLI"})]}),n.codexCli&&d.jsxs(Jr,{onClick:R,className:"flex items-center gap-2",children:[d.jsx("img",{src:"https://inspector-cdn.mcp-use.com/providers/openai.png",alt:"Codex",className:"h-4 w-4"}),d.jsx("span",{className:"min-w-0 max-w-full whitespace-nowrap",children:"Codex CLI"})]})]})]}),d.jsx(tl,{open:l,onOpenChange:u,children:d.jsx(nl,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:C()})})]})}function ZF({className:e,state:t="collapsed",href:n="https://mcp-use.com"}){const[r,a]=y.useState(!1),o=.2,i=.7,l=.6,u=4,f=o+i+l,m=0,h=o/f,g=(o+i)/f,b=1;return d.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:Ue("flex items-center transition-opacity -my-3",t==="expanded"?"space-x-2":"",e),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[d.jsx("div",{className:"relative",children:d.jsxs(Fa.svg,{viewBox:"0 0 303 303",initial:"rest",animate:r?"hover":"rest",className:Ue("text-foreground",t==="expanded"?"size-[40px]":"size-[20px]"),children:[d.jsxs(Fa.g,{variants:{rest:{opacity:1},hover:{opacity:[1,0,0,1],transition:{duration:f,times:[m,h,g,b],ease:"easeInOut"}}},fill:"currentColor",fillRule:"nonzero",stroke:"currentColor",strokeWidth:u,strokeLinecap:"round",strokeLinejoin:"round",children:[d.jsx("path",{d:"m105.5 34.8.6.6c9.5 9.5 14.4 21.9 14.6 34.4a112.6 112.6 0 0 0 112.2 112.1h.6c12 .4 24 5.1 33.2 14.1l.6.6a50 50 0 0 1-70.1 71.3l-.6-.6A49.9 49.9 0 0 1 182 230 112.6 112.6 0 0 0 73.4 120.7h-.8a49.9 49.9 0 0 1-36.7-14l-.5-.6a50 50 0 0 1-.6-70.2l.6-.5a50 50 0 0 1 69.5-1.2l.6.6Z"}),d.jsx("circle",{cx:"70.3",cy:"232.3",r:"50"}),d.jsx("circle",{cx:"232.3",cy:"70.3",r:"50"})]}),d.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:u,strokeLinecap:"round",strokeLinejoin:"round",children:[d.jsx(yTe,{d:"m105.5 34.8.6.6c9.5 9.5 14.4 21.9 14.6 34.4a112.6 112.6 0 0 0 112.2 112.1h.6c12 .4 24 5.1 33.2 14.1l.6.6a50 50 0 0 1-70.1 71.3l-.6-.6A49.9 49.9 0 0 1 182 230 112.6 112.6 0 0 0 73.4 120.7h-.8a49.9 49.9 0 0 1-36.7-14l-.5-.6a50 50 0 0 1-.6-70.2l.6-.5a50 50 0 0 1 69.5-1.2l.6.6Z",times:{T0:m,T1:h,T2:g,T3:b},total:f}),d.jsx(qF,{cx:70.3,cy:232.3,r:50,times:{T0:m,T1:h,T2:g,T3:b},total:f}),d.jsx(qF,{cx:232.3,cy:70.3,r:50,times:{T0:m,T1:h,T2:g,T3:b},total:f})]})]})}),t==="expanded"&&d.jsxs("div",{className:"font-ubuntu flex-col items-start -space-y-1 mr-3 hidden xl:flex",children:[d.jsx("h1",{className:"text-xl font-medium",children:"mcp-use"}),d.jsx("span",{className:"text-lg text-muted-foreground tracking-wide font-sans font-light",children:"Inspector"})]})]})}function yTe({d:e,times:t,total:n}){const{T0:r,T1:a,T2:o,T3:i}=t;return d.jsx(Fa.path,{d:e,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:n,times:[r,a,o,i],ease:"easeInOut"}}}})}function qF({cx:e,cy:t,r:n,times:r,total:a}){const{T0:o,T1:i,T2:l,T3:u}=r;return d.jsx(Fa.circle,{cx:e,cy:t,r:n,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:a,times:[o,i,l,u],ease:"easeInOut"}}}})}function Kb({open:e,onOpenChange:t,serverUrl:n,serverName:r,serverId:a,headers:o,language:i}){const{prismStyle:l}=LI(),[u,f]=y.useState(!1),m=i==="typescript"?fxe(n,r,a,o):pxe(n,r,a,o),h=async()=>{await navigator.clipboard.writeText(m),f(!0),setTimeout(()=>f(!1),2e3)},g=i==="typescript"?"TypeScript":"Python",b=i==="typescript"?"npm install mcp-use":"pip install mcp-use";return d.jsx(tl,{open:e,onOpenChange:t,children:d.jsxs(nl,{className:"max-w-[90vw] max-h-[90vh] overflow-hidden flex flex-col",children:[d.jsxs(ls,{children:[d.jsxs(cs,{children:["Add to ",g," SDK"]}),d.jsxs(Fp,{children:["Copy the following code to integrate this server into your"," ",g," application using the mcp-use SDK."]})]}),d.jsxs("div",{className:"space-y-4 overflow-y-auto flex-1 min-h-0",children:[d.jsxs("div",{children:[d.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Instructions"}),d.jsxs("ol",{className:"space-y-2 text-xs text-muted-foreground",children:[d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"1."}),d.jsxs("span",{children:["Install the mcp-use package:"," ",d.jsx("code",{className:"text-foreground",children:b})]})]}),d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"2."}),d.jsxs("span",{children:["Copy the following code into your ",g," project:"]})]})]})]}),d.jsxs("div",{className:"relative w-full overflow-x-auto overflow-y-auto max-h-[60vh]",children:[d.jsx("div",{className:"absolute top-2 right-2 z-10",children:d.jsx(Me,{variant:"ghost",size:"sm",className:"h-7 px-2 bg-background hover:bg-accent border border-border",onClick:h,children:u?d.jsx(Or,{className:"size-3.5 text-green-600"}):d.jsx(wr,{className:"size-3.5"})})}),d.jsx(Em,{language:i,style:l,customStyle:{margin:0,padding:"1rem",paddingRight:"3rem",borderRadius:"0.5rem",fontSize:"0.75rem",background:"var(--muted)",width:"100%",maxWidth:"100%",overflow:"auto"},wrapLines:!0,wrapLongLines:!0,PreTag:"div",children:m})]})]})]})})}function GW({ref:e,shimmerColor:t,shimmerSize:n="0.05em",shimmerDuration:r="3s",borderRadius:a="100px",background:o,className:i,children:l,...u}){const{resolvedTheme:f}=Nw(),m=f==="dark"?"#000000":"#ffffff",h=f==="dark"?"rgba(255, 255, 255, 1)":"rgba(0, 0, 0, 1)",g=t||m,b=o||h;return d.jsxs("button",{style:{"--spread":"90deg","--shimmer-color":g,"--radius":a,"--speed":r,"--cut":n,"--bg":b},className:Ue("group relative z-0 flex cursor-pointer items-center justify-center overflow-hidden [border-radius:var(--radius)] border px-6 py-3 whitespace-nowrap [background:var(--bg)]","transform-gpu transition-transform duration-300 ease-in-out active:translate-y-px",f==="dark"?"border-black/10 text-black":"border-white/10 text-white",i),ref:e,...u,children:[d.jsx("div",{className:Ue("-z-30 blur-[2px]","[container-type:size] absolute inset-0 overflow-visible"),children:d.jsx("div",{className:"animate-shimmer-slide absolute inset-0 [aspect-ratio:1] h-[100cqh] [border-radius:0] [mask:none]",children:d.jsx("div",{className:"animate-spin-around absolute -inset-full w-auto [translate:0_0] rotate-0 [background:conic-gradient(from_calc(270deg-(var(--spread)*0.5)),transparent_0,var(--shimmer-color)_var(--spread),transparent_var(--spread))]"})})}),l,d.jsx("div",{className:Ue("absolute inset-0 size-full","rounded-2xl px-4 py-1.5 text-sm font-medium","transform-gpu transition-all duration-300 ease-in-out",f==="dark"?"shadow-[inset_0_-8px_10px_#0000001f] group-hover:shadow-[inset_0_-6px_10px_#0000003f] group-active:shadow-[inset_0_-10px_10px_#0000003f]":"shadow-[inset_0_-8px_10px_#ffffff1f] group-hover:shadow-[inset_0_-6px_10px_#ffffff3f] group-active:shadow-[inset_0_-10px_10px_#ffffff3f]")}),d.jsx("div",{className:Ue("absolute [inset:var(--cut)] -z-20 [border-radius:var(--radius)] [background:var(--bg)]")})]})}GW.displayName="ShimmerButton";function XF({status:e}){const t=o=>{switch(o){case"ready":return{color:"bg-emerald-500",ringColor:"ring-emerald-500",tooltip:"Connected"};case"failed":return{color:"bg-red-500",ringColor:"ring-red-500",tooltip:"Failed"};default:return{color:"bg-yellow-500",ringColor:"ring-yellow-500",tooltip:o}}},{color:n,ringColor:r,tooltip:a}=t(e);return d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:`absolute w-2 h-2 rounded-full ${r} animate-ping`}),d.jsx("div",{className:`relative w-2 h-2 rounded-full ${n}`})]})}),d.jsx(Yt,{children:d.jsx("p",{children:a})})]})}function JF({connections:e,selectedServer:t,onServerSelect:n,onOpenConnectionOptions:r,mobileMode:a=!1}){const o=bl(),[i,l]=y.useState(!1),[u,f]=y.useState(null),m=h=>{const g=e.find(b=>b.id===h);if(!g||g.state!=="ready"){At.error("Server is not connected and cannot be inspected");return}n(h)};return a?d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("div",{className:"relative",children:d.jsxs(im,{children:[d.jsx(lm,{asChild:!0,children:d.jsxs(Me,{variant:"ghost",className:"h-11 px-2 bg-black dark:bg-white text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200 flex items-center gap-1.5",children:[t?d.jsx(Hu,{server:t,size:"md"}):d.jsx(WH,{className:"h-5 w-5"}),d.jsx(hs,{className:"h-4 w-4"})]})}),d.jsxs(jd,{className:"w-[calc(100vw-2rem)] sm:w-[300px]",align:"start",children:[d.jsx(i_,{className:"cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:()=>o("/"),children:"MCP Servers"}),d.jsx(Lu,{}),e.length===0?d.jsx("div",{className:"px-2 py-4 text-sm text-muted-foreground dark:text-zinc-400 text-center",children:"No servers connected. Go to the dashboard to add one."}):e.map(h=>d.jsxs(Jr,{onClick:()=>m(h.id),className:"flex items-center gap-3",children:[d.jsx(Hu,{server:h,size:"sm"}),d.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[d.jsx("div",{className:"font-medium",children:h.name}),d.jsx(XF,{status:h.state})]}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(Me,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:g=>{g.stopPropagation(),f(h),l(!0)},children:d.jsx(Up,{className:"h-3 w-3"})}),d.jsx(Me,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:g=>{g.stopPropagation(),r(h.id)},children:d.jsx(Xu,{className:"h-3 w-3"})})]})]},h.id)),d.jsx(Lu,{}),d.jsx(Jr,{onClick:()=>o("/"),children:d.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:"+ Add new server"})})]})]})}),d.jsx(V_,{open:i,onOpenChange:l,connection:u})]}):d.jsx("div",{className:"flex items-center gap-2",children:d.jsxs("div",{className:"relative",children:[d.jsxs(im,{children:[d.jsx(lm,{asChild:!0,children:d.jsxs(GW,{className:Ue("min-w-0 sm:min-w-[200px] p-0 px-1 text-sm h-11 justify-start bg-black dark:bg-white text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200",!t&&"pl-4",t&&"pr-20"),children:[t&&d.jsx(Hu,{server:t,size:"md",className:"mr-2"}),d.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[d.jsx("span",{className:"truncate lg:max-w-[120px] xl:max-w-none",children:t?t.serverInfo?.title||t.serverInfo?.name||t.name:"Select server to inspect"}),t&&d.jsx("div",{className:"flex items-center gap-2",children:t.error&&t.state!=="ready"?d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx("button",{onClick:h=>{h.stopPropagation()},className:"w-2 h-2 rounded-full bg-rose-500 animate-status-pulse-red hover:bg-rose-600 transition-colors",title:"Click to copy error message","aria-label":"Copy error message to clipboard"})}),d.jsx(Yt,{children:d.jsx("p",{className:"max-w-xs",children:t.error})})]}):d.jsx("div",{className:`w-2 h-2 rounded-full ${t.state==="ready"?"bg-emerald-600 animate-status-pulse":t.state==="failed"?"bg-rose-600 animate-status-pulse-red":"bg-yellow-500 animate-status-pulse-yellow"}`})})]})]})}),t&&d.jsxs("div",{className:"absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1",children:[d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx("button",{type:"button",onClick:()=>{f(t),l(!0)},className:"p-1.5 hover:bg-white/10 dark:hover:bg-black/10 rounded-full transition-colors text-white dark:text-black","aria-label":"View server info",children:d.jsx(Up,{className:"h-4 w-4"})})}),d.jsx(Yt,{children:d.jsx("p",{children:"View server info"})})]}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx("button",{type:"button",onClick:()=>{r(t.id)},className:"p-1.5 hover:bg-white/10 dark:hover:bg-black/10 rounded-full transition-colors text-white dark:text-black","aria-label":"Edit connection settings",children:d.jsx(Xu,{className:"h-4 w-4"})})}),d.jsx(Yt,{children:d.jsx("p",{children:"Edit connection settings"})})]})]}),d.jsxs(jd,{className:"w-[calc(100vw-2rem)] sm:w-[300px]",align:"start",children:[d.jsx(i_,{className:"cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:()=>o("/"),children:"MCP Servers"}),d.jsx(Lu,{}),e.length===0?d.jsx("div",{className:"px-2 py-4 text-sm text-muted-foreground dark:text-zinc-400 text-center",children:"No servers connected. Go to the dashboard to add one."}):e.map(h=>d.jsxs(Jr,{onClick:()=>m(h.id),className:"flex items-center gap-3",children:[d.jsx(Hu,{server:h,size:"sm"}),d.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[d.jsx("div",{className:"font-medium",children:h.serverInfo?.title||h.serverInfo?.name||h.name}),d.jsx(XF,{status:h.state})]}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(Me,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:g=>{g.stopPropagation(),f(h),l(!0)},children:d.jsx(Up,{className:"h-3 w-3"})}),d.jsx(Me,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:g=>{g.stopPropagation(),r(h.id)},children:d.jsx(Xu,{className:"h-3 w-3"})})]})]},h.id)),d.jsx(Lu,{}),d.jsx(Jr,{onClick:()=>o("/"),children:d.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:"+ Add new server"})})]})]}),d.jsx(V_,{open:i,onOpenChange:l,connection:u})]})})}function QF({className:e}){const{theme:t,setTheme:n}=Nw(),r=y.useRef(null),a=()=>t==="system"?d.jsx(EU,{className:"size-4"}):t==="light"?d.jsx(TU,{className:"size-4"}):d.jsx(SU,{className:"size-4"}),o=async i=>{const l=r.current;if(!l){n(i);return}if(typeof document<"u"&&"startViewTransition"in document){await document.startViewTransition(()=>{ef.flushSync(()=>{n(i)})}).ready;const{top:u,left:f,width:m,height:h}=l.getBoundingClientRect(),g=u+h/2,b=f+m/2,E=window.innerWidth-f,x=window.innerHeight-u,w=Math.hypot(Math.max(f,E),Math.max(u,x));document.documentElement.animate({clipPath:[`circle(0px at ${b}px ${g}px)`,`circle(${w}px at ${b}px ${g}px)`]},{duration:700,easing:"ease-in-out",pseudoElement:"::view-transition-new(root)"})}else n(i)};return d.jsxs(im,{children:[d.jsx(lm,{asChild:!0,children:d.jsx(Me,{ref:r,variant:"ghost",size:"sm",className:Ue("p-2 hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full transition-colors",e),"aria-label":"Toggle theme",children:a()})}),d.jsx(jd,{align:"end",className:"min-w-0",children:d.jsxs(mce,{value:t,onValueChange:i=>o(i),children:[d.jsxs(ay,{value:"light",className:"pl-2 pr-0 flex items-center gap-2 justify-end",children:[d.jsx("span",{children:"Light"}),d.jsx(TU,{className:"mr-2 h-4 w-4"})]}),d.jsxs(ay,{value:"dark",className:"pl-2 pr-0 flex items-center gap-2 justify-end",children:[d.jsx("span",{children:"Dark"}),d.jsx(SU,{className:"mr-2 h-4 w-4"})]}),d.jsxs(ay,{value:"system",className:"pl-2 pr-0 flex items-center gap-2 justify-end",children:[d.jsx("span",{children:"System"}),d.jsx(EU,{className:"mr-2 h-4 w-4"})]})]})})]})}const e4=[{id:"tools",label:"Tools",icon:dc},{id:"prompts",label:"Prompts",icon:pm},{id:"resources",label:"Resources",icon:Mue},{id:"sampling",label:"Sampling",icon:BH},{id:"elicitation",label:"Elicitation",icon:KH},{id:"notifications",label:"Notifications",icon:KN},{id:"chat",label:"Chat",icon:Yue}];function t4(e,t){return e==="tools"?t.tools.length:e==="prompts"?t.prompts.length:e==="resources"?t.resources.length:e==="sampling"?t.pendingSamplingRequests?.length||0:e==="elicitation"?t.pendingElicitationRequests?.length||0:e==="notifications"?t.unreadNotificationCount:0}function n4(e,t,n){const r=["sampling","elicitation","notifications"];return n&&t>0&&r.includes(e)}function vTe({collapsed:e,onToggle:t}){return d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx("button",{onClick:t,className:Ue("shrink-0 p-1.5 rounded-md transition-all duration-500 ease-in-out cursor-pointer","text-muted-foreground hover:text-foreground","hover:bg-zinc-100 dark:hover:bg-zinc-800","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"),"aria-label":e?"Expand tabs":"Collapse tabs",type:"button",children:e?d.jsx(zH,{className:"h-4 w-4 transition-transform duration-500 ease-in-out"}):d.jsx(tw,{className:"h-4 w-4 transition-transform duration-500 ease-in-out"})})}),d.jsx(Yt,{children:d.jsx("p",{children:e?"Expand tabs":"Collapse tabs"})})]})}function wTe({connections:e,selectedServer:t,activeTab:n,onServerSelect:r,onTabChange:a,onCommandPaletteOpen:o,onOpenConnectionOptions:i,embedded:l=!1}){const{tunnelUrl:u}=kc(),f=t&&u,[m,h]=y.useState(!1),[g,b]=y.useState(!1),[E,x]=y.useState(!1),[w,S]=y.useState(!0),_=async()=>{if(u)try{await navigator.clipboard.writeText(`${u}/mcp`),h(!0),At.success("Tunnel URL copied to clipboard"),setTimeout(()=>h(!1),2e3)}catch{At.error("Failed to copy URL")}};return d.jsxs("header",{className:"w-full mx-auto",children:[d.jsxs("div",{className:"flex lg:hidden flex-col gap-3",children:[d.jsxs("div",{className:"flex items-center justify-between w-full",children:[!l&&d.jsx("div",{className:"flex-1 flex justify-start",children:d.jsx(JF,{connections:e,selectedServer:t,onServerSelect:r,onOpenConnectionOptions:i,mobileMode:!0})}),!l&&d.jsx("div",{className:"flex-shrink-0 flex justify-center",children:d.jsx("div",{className:"scale-150",children:d.jsx(ZF,{state:"collapsed"})})}),!l&&d.jsxs("div",{className:"flex-1 flex justify-end items-center gap-2",children:[t&&(()=>{const T=t.serverInfo?.title||t.serverInfo?.name||t.name;return d.jsxs(d.Fragment,{children:[d.jsx(YF,{serverConfig:{url:u?`${u}/mcp`:t.url,name:T,headers:t.customHeaders,serverId:t.id},onSuccess:k=>At.success(`Opening in ${k}...`),onError:k=>At.error(`Failed: ${k.message}`),additionalItems:[{id:"ts-sdk",label:"TypeScript SDK",icon:d.jsx("img",{src:"https://cdn.simpleicons.org/typescript",alt:"TypeScript",className:"h-4 w-4"}),onClick:()=>b(!0)},{id:"py-sdk",label:"Python SDK",icon:d.jsx("img",{src:"https://cdn.simpleicons.org/python",alt:"Python",className:"h-4 w-4"}),onClick:()=>x(!0)}],trigger:d.jsxs(Me,{variant:"ghost",className:"bg-zinc-200 dark:bg-zinc-800 hover:bg-zinc-300 dark:hover:bg-zinc-700 rounded-full transition-colors px-3 flex items-center justify-center p-2","aria-label":"Add to Client",children:[d.jsxs("span",{className:"xl:hidden hidden sm:flex items-center gap-1",children:[d.jsx(mm,{className:"size-3"}),"Client"]}),d.jsxs("span",{className:"hidden xl:flex items-center gap-1",children:["Add to Client",d.jsx(hs,{className:"size-3"})]})]})}),d.jsx(Kb,{open:g,onOpenChange:b,serverUrl:u?`${u}/mcp`:t.url,serverName:T,serverId:void 0,headers:t.customHeaders,language:"typescript"}),d.jsx(Kb,{open:E,onOpenChange:x,serverUrl:u?`${u}/mcp`:t.url,serverName:T,serverId:void 0,headers:t.customHeaders,language:"python"})]})})(),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",asChild:!0,children:d.jsx("a",{href:"https://github.com/mcp-use/mcp-use",target:"_blank",rel:"noopener noreferrer",className:"p-2","aria-label":"GitHub",children:d.jsx(KF,{className:"h-4 w-4"})})})}),d.jsx(Yt,{children:d.jsx("p",{children:"Give us a star ⭐"})})]}),d.jsx(QF,{})]})]}),t&&d.jsx("div",{className:"w-full",children:d.jsx($T,{value:n,onValueChange:T=>a(T),collapsed:w,onCollapsedChange:S,children:d.jsx(UT,{className:"w-full justify-center",children:e4.map(T=>{const k=t4(T.id,t),R=n4(T.id,k,w);return d.jsxs(zT,{value:T.id,icon:T.icon,showDot:R,className:Ue("[&>svg]:mr-0 flex-1 flex-row gap-2 relative",w&&"pl-2"),children:[k>0&&!w&&d.jsx("span",{className:Ue(n===T.id?"dark:bg-black":"dark:bg-zinc-700","bg-zinc-200 text-zinc-700 dark:text-zinc-300 text-[10px] px-1.5 py-0.5 rounded-full font-medium"),children:k}),d.jsx("span",{className:"sr-only",children:T.label})]},T.id)})})})})]}),d.jsxs("div",{className:"hidden lg:flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"flex items-center flex-wrap gap-2 md:space-x-6 space-x-2",children:[!l&&d.jsx(JF,{connections:e,selectedServer:t,onServerSelect:r,onOpenConnectionOptions:i}),t&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx($T,{value:n,onValueChange:T=>a(T),collapsed:w,onCollapsedChange:S,children:d.jsx(UT,{className:"overflow-x-auto",collapsible:!0,children:e4.map(T=>{const k=t4(T.id,t),R=k>0?`${T.label} (${k})`:T.label,A=n4(T.id,k,w);return d.jsx(zT,{value:T.id,icon:T.icon,showDot:A,className:Ue("[&>svg]:mr-0 lg:[&>svg]:mr-2 relative",w&&"pl-4"),title:R,children:d.jsxs("div",{className:"items-center gap-2 hidden lg:flex",children:[T.label,k>0&&d.jsx("span",{className:Ue(n===T.id?" dark:bg-black ":"dark:bg-zinc-700","bg-zinc-200 text-zinc-700 dark:text-zinc-300 text-xs px-2 py-0.5 rounded-full font-medium"),children:k})]})})})})}),d.jsx(vTe,{collapsed:w,onToggle:()=>S(!w)})]}),f&&d.jsxs(o7,{children:[d.jsx(s7,{asChild:!0,children:d.jsxs("button",{className:"flex items-center gap-2 px-3 py-1.5 bg-gradient-to-r from-purple-500/10 to-pink-500/10 dark:from-purple-500/20 dark:to-pink-500/20 border border-purple-500/30 dark:border-purple-500/40 rounded-full hover:from-purple-500/20 hover:to-pink-500/20 dark:hover:from-purple-500/30 dark:hover:to-pink-500/30 transition-colors cursor-pointer",children:[d.jsx(hm,{className:"size-4 text-purple-600 dark:text-purple-400 animate-pulse"}),d.jsx("span",{className:"text-xs font-medium text-purple-700 dark:text-purple-300 hidden lg:inline",children:"Tunnel"})]})}),d.jsx(gO,{className:"w-[calc(100vw-2rem)] sm:w-96",align:"start",children:d.jsxs("div",{className:"space-y-4",children:[d.jsxs("div",{children:[d.jsxs("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:[d.jsx(hm,{className:"size-4 text-purple-600 dark:text-purple-400"}),"Tunnel URL"]}),d.jsxs("div",{className:"flex items-center gap-2 p-2 py-0 bg-muted rounded-full",children:[d.jsxs("code",{className:"flex-1 text-[10px] font-mono",children:[u,"/mcp"]}),d.jsx(Me,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:_,children:m?d.jsx(Or,{className:"size-3.5 text-green-600"}):d.jsx(wr,{className:"size-3.5"})})]})]}),d.jsxs("div",{children:[d.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Use in ChatGPT"}),d.jsxs("ol",{className:"space-y-2 text-xs text-muted-foreground",children:[d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"1."}),d.jsxs("span",{children:["Enable"," ",d.jsx("span",{className:"font-medium text-foreground",children:"dev mode"})," ","from settings"]})]}),d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"2."}),d.jsxs("span",{children:["In"," ",d.jsx("span",{className:"font-medium text-foreground",children:"App & Connectors"})," ","click on"," ",d.jsx("span",{className:"font-medium text-foreground",children:"create"})]})]}),d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"3."}),d.jsx("span",{children:"Use the tunnel URL in the input"})]})]})]})]})})]})]}),!l&&d.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-shrink-0",children:[t&&(()=>{const T=t.serverInfo?.title||t.serverInfo?.name||t.name;return d.jsxs(d.Fragment,{children:[d.jsx(YF,{serverConfig:{url:u?`${u}/mcp`:t.url,name:T,headers:t.customHeaders,serverId:t.id},onSuccess:k=>At.success(`Opening in ${k}...`),onError:k=>At.error(`Failed: ${k.message}`),additionalItems:[{id:"ts-sdk",label:"TypeScript SDK",icon:d.jsx("img",{src:"https://cdn.simpleicons.org/typescript",alt:"TypeScript",className:"h-4 w-4"}),onClick:()=>b(!0)},{id:"py-sdk",label:"Python SDK",icon:d.jsx("img",{src:"https://cdn.simpleicons.org/python",alt:"Python",className:"h-4 w-4"}),onClick:()=>x(!0)}],trigger:d.jsxs(Me,{variant:"ghost",className:"bg-zinc-200 dark:bg-zinc-800 hover:bg-zinc-300 dark:hover:bg-zinc-700 rounded-full transition-colors px-3 flex items-center justify-center","aria-label":"Add to Client",children:[d.jsxs("span",{className:"xl:hidden hidden sm:flex items-center gap-1",children:[d.jsx(mm,{className:"size-3"}),"Client"]}),d.jsxs("span",{className:"hidden xl:flex items-center gap-1",children:["Add to Client",d.jsx(hs,{className:"size-3"})]})]})}),d.jsx(Kb,{open:g,onOpenChange:b,serverUrl:u?`${u}/mcp`:t.url,serverName:T,serverId:void 0,headers:t.customHeaders,language:"typescript"}),d.jsx(Kb,{open:E,onOpenChange:x,serverUrl:u?`${u}/mcp`:t.url,serverName:T,serverId:void 0,headers:t.customHeaders,language:"python"})]})})(),d.jsx(QF,{}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsxs(Me,{variant:"ghost",className:"hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full px-1 -mx-3 flex gap-1",onClick:o,children:[d.jsx(yue,{className:"size-4"}),d.jsx("span",{className:"text-base font-mono hidden sm:inline",children:"K"})]})}),d.jsx(Yt,{children:d.jsx("p",{children:"Command Palette"})})]}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",asChild:!0,children:d.jsxs("a",{href:"https://github.com/mcp-use/mcp-use",className:"flex items-center gap-2",target:"_blank",rel:"noopener noreferrer",children:[d.jsx(KF,{className:"h-4 w-4"}),d.jsx("span",{className:"hidden xl:inline",children:"Github"})]})})}),d.jsx(Yt,{children:d.jsx("p",{children:"Give us a star ⭐"})})]}),d.jsx(ZF,{state:"expanded"})]})]})]})}function xTe({children:e}){const t=bl(),n=Aa(),{servers:r,addServer:a,removeServer:o,updateServer:i,storageLoaded:l}=Wm(),u=y.useCallback((D,$,G,W)=>{a(D,{url:D,name:$,proxyConfig:G,transportType:W,preventAutoAuth:!0})},[a]),f=y.useCallback(async(D,$)=>{try{await i(D,$)}catch(G){console.error(`[Layout] Failed to update connection ${D}:`,G)}},[i]),{selectedServerId:m,setSelectedServerId:h,activeTab:g,setActiveTab:b,navigateToItem:E,setTunnelUrl:x,tunnelUrl:w,isEmbedded:S,embeddedConfig:_,setEmbeddedMode:T}=kc(),[k,R]=y.useState(!1),[A,C]=y.useState(null),O=U0e();y.useEffect(()=>{const D=new URLSearchParams(n.search),$=D.get("embedded")==="true",G=D.get("embeddedConfig");if($){let W={};if(G)try{W=JSON.parse(G)}catch(re){console.error("Failed to parse embeddedConfig:",re)}T(!0,W)}},[]),y.useEffect(()=>{const $=new URLSearchParams(n.search).get("tunnelUrl");x($)},[n.search,x]),y.useEffect(()=>{const $=new URLSearchParams(n.search).get("tab");$&&["tools","prompts","resources","chat","sampling","elicitation","notifications"].includes($)&&b($)},[n.search,b]),y.useEffect(()=>{const D=W=>{const pe=W.detail.requestId;m&&E(m,"sampling",pe)},$=W=>{const pe=W.detail.requestId;m&&E(m,"elicitation",pe)},G=W=>{const pe=W.detail.toolName;m&&pe?E(m,"tools",pe):m&&b("tools")};return window.addEventListener("navigate-to-sampling",D),window.addEventListener("navigate-to-elicitation",$),window.addEventListener("navigate-to-tool-result",G),()=>{window.removeEventListener("navigate-to-sampling",D),window.removeEventListener("navigate-to-elicitation",$),window.removeEventListener("navigate-to-tool-result",G)}},[m,b,E]);const M=y.useRef(null),L=y.useRef(null),j=y.useRef(null),{isAutoConnecting:B}=$0e({connections:r,addConnection:u,removeConnection:o,configLoaded:l,embedded:S}),K=y.useCallback(D=>{ra.getInstance().capture(new zce({trigger:D})).catch(()=>{}),R(!0)},[]),Z=D=>{const $=r.find(me=>me.id===D);if(!$||$.state!=="ready"){At.error("Server is not connected and cannot be inspected");return}h(D);const G=new URLSearchParams(n.search),W=G.get("tunnelUrl"),re=G.get("tab"),pe=new URLSearchParams;pe.set("server",D),W&&pe.set("tunnelUrl",W),re&&pe.set("tab",re),t(`/?${pe.toString()}`)},te=y.useCallback(D=>{C(D)},[]),V=y.useCallback(D=>{A&&(D.url!==A?(o(A),u(D.url,D.name,D.proxyConfig,D.transportType)):f(A,{name:D.name,proxyConfig:D.proxyConfig,transportType:D.transportType}),C(null),At.success("Connection settings updated"))},[A,o,u,f]),Y=(D,$,G)=>{if(console.warn("[Layout] handleCommandPaletteNavigate called:",{tab:D,itemName:$,serverId:G}),G){const W=r.find(X=>X.id===G);if(console.warn("[Layout] Server lookup:",{serverId:G,serverFound:!!W,serverState:W?.state}),!W||W.state!=="ready"){console.warn("[Layout] Server not ready, showing error"),At.error("Server is not connected and cannot be inspected");return}console.warn("[Layout] Calling navigateToItem:",{serverId:G,tab:D,itemName:$}),E(G,D,$);const re=new URLSearchParams(n.search),pe=re.get("tunnelUrl"),me=re.get("tab"),ne=new URLSearchParams;ne.set("server",G),pe&&ne.set("tunnelUrl",pe),D?ne.set("tab",D):me&&ne.set("tab",me);const J=`/?${ne.toString()}`;console.warn("[Layout] Navigating to:",J),t(J)}else console.warn("[Layout] No serverId, just updating tab to:",D),b(D)},F=r.find(D=>D.id===m),ae=F?F.tools.map(D=>({...D,_serverId:F.id})):r.flatMap(D=>D.state==="ready"?D.tools.map($=>({...$,_serverId:D.id,_serverName:D.name})):[]),ee=F?F.prompts.map(D=>({...D,_serverId:F.id})):r.flatMap(D=>D.state==="ready"?D.prompts.map($=>({...$,_serverId:D.id,_serverName:D.name})):[]),P=F?F.resources.map(D=>({...D,_serverId:F.id})):r.flatMap(D=>D.state==="ready"?D.resources.map($=>({...$,_serverId:D.id,_serverName:D.name})):[]);if(y.useEffect(()=>{const $=new URLSearchParams(n.search).get("server"),G=$?decodeURIComponent($):null;G!==m&&h(G)},[n.search,m,h]),y.useEffect(()=>{const $=new URLSearchParams(n.search).get("server");if(!$)return;const G=decodeURIComponent($),W=r.find(re=>re.id===G);if(!W){const re=setTimeout(()=>t("/"),3e3);return()=>clearTimeout(re)}if(W.state==="failed"){const re=setTimeout(()=>t("/"),2e3);return()=>clearTimeout(re)}},[n.search,t,r]),NG({onCommandPalette:()=>K("keyboard"),onToolsTab:()=>{F&&b("tools")},onPromptsTab:()=>{F&&b("prompts")},onResourcesTab:()=>{F&&b("resources")},onChatTab:()=>{F&&b("chat")},onHome:()=>{t("/")},onFocusSearch:()=>{g==="tools"&&M.current?M.current.focusSearch():g==="prompts"&&L.current?L.current.focusSearch():g==="resources"&&j.current&&j.current.focusSearch()},onBlurSearch:()=>{g==="tools"&&M.current?M.current.blurSearch():g==="prompts"&&L.current?L.current.blurSearch():g==="resources"&&j.current&&j.current.blurSearch()}}),B)return d.jsx("div",{className:"h-screen bg-white dark:bg-zinc-900 flex items-center justify-center",children:d.jsxs("div",{className:"flex flex-col items-center gap-4",children:[d.jsx(gs,{className:"h-8 w-8 text-zinc-600 dark:text-zinc-400"}),d.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Connecting to MCP server..."})]})});const H=S?{backgroundColor:_.backgroundColor||"#f3f3f3",padding:_.padding||"0.5rem"}:{},U=S?"h-screen flex flex-col gap-2 sm:gap-4":"h-screen bg-[#f3f3f3] dark:bg-black flex flex-col px-2 py-2 sm:px-4 sm:py-4 gap-2 sm:gap-4";return d.jsx(WN,{children:d.jsxs("div",{className:U,style:H,children:[d.jsx(wTe,{connections:r,selectedServer:F,activeTab:g,onServerSelect:Z,onTabChange:b,onCommandPaletteOpen:()=>K("button"),onOpenConnectionOptions:te,embedded:S}),d.jsx("main",{className:"flex-1 w-full mx-auto bg-white dark:bg-black rounded-2xl border border-zinc-200 dark:border-zinc-700 p-0 overflow-auto",children:d.jsx(hTe,{selectedServer:F,activeTab:g,toolsSearchRef:M,promptsSearchRef:L,resourcesSearchRef:j,children:e})}),d.jsx(hxe,{isOpen:k,onOpenChange:R,tools:ae,prompts:ee,resources:P,savedRequests:O,connections:r,selectedServer:F,tunnelUrl:w,onNavigate:Y,onServerSelect:Z}),d.jsx(V8,{connection:A&&r.find(D=>D.id===A)||null,open:A!==null,onOpenChange:D=>{D||C(null)},onConnect:V})]})})}function ETe(){const[e,t]=y.useState("processing"),[n,r]=y.useState("");return y.useEffect(()=>{console.log("[OAuthCallback] Component mounted, handling authorization..."),console.log("[OAuthCallback] Current URL:",window.location.href),xN().then(()=>{console.log("[OAuthCallback] Authorization successful"),t("success")}).catch(a=>{console.error("[OAuthCallback] Authorization failed:",a),t("error"),r(a instanceof Error?a.message:String(a))})},[]),e==="processing"?d.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:d.jsxs("div",{className:"flex flex-col items-center gap-4",children:[d.jsx(cl,{className:"h-8 w-8 animate-spin text-zinc-600 dark:text-zinc-400"}),d.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Completing authentication..."})]})}):e==="error"?d.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:d.jsxs("div",{className:"max-w-md p-6",children:[d.jsx("h1",{className:"text-xl font-semibold text-red-600 dark:text-red-400 mb-2",children:"Authentication Error"}),d.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400 mb-4",children:n}),d.jsx("p",{className:"text-xs text-zinc-500 dark:text-zinc-500",children:"You can close this window and try again."})]})}):d.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:d.jsxs("div",{className:"max-w-md p-6",children:[d.jsx("h1",{className:"text-xl font-semibold text-green-600 dark:text-green-400 mb-2",children:"Authentication Successful!"}),d.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Redirecting you back..."})]})})}var STe=(e,t,n,r,a,o,i,l)=>{let u=document.documentElement,f=["light","dark"];function m(b){(Array.isArray(e)?e:[e]).forEach(E=>{let x=E==="class",w=x&&o?a.map(S=>o[S]||S):a;x?(u.classList.remove(...w),u.classList.add(o&&o[b]?o[b]:b)):u.setAttribute(E,b)}),h(b)}function h(b){l&&f.includes(b)&&(u.style.colorScheme=b)}function g(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)m(r);else try{let b=localStorage.getItem(t)||n,E=i&&b==="system"?g():b;m(E)}catch{}},_Te=y.createContext(void 0),TTe={setTheme:e=>{},themes:[]},NTe=()=>{var e;return(e=y.useContext(_Te))!=null?e:TTe};y.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:a,defaultTheme:o,value:i,themes:l,nonce:u,scriptProps:f})=>{let m=JSON.stringify([n,t,o,e,l,i,r,a]).slice(1,-1);return y.createElement("script",{...f,suppressHydrationWarning:!0,nonce:typeof window>"u"?u:"",dangerouslySetInnerHTML:{__html:`(${STe.toString()})(${m})`}})});function CTe({...e}){const{theme:t="system"}=NTe();return d.jsx(Ume,{theme:t,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...e})}function RTe(){const t=new URLSearchParams(window.location.search).get("embedded")==="true",n=y.useMemo(()=>t?void 0:new eae("mcp-inspector-connections"),[t]);return d.jsx(Xge,{children:d.jsx(RB,{storageProvider:n,enableRpcLogging:!0,defaultAutoProxyFallback:{enabled:!0,proxyAddress:`${window.location.origin}/inspector/api/proxy`},onServerAdded:(r,a)=>{console.log("[Inspector] Server added:",r,a.state)},onServerRemoved:r=>{console.log("[Inspector] Server removed:",r)},onServerStateChange:(r,a)=>{console.log("[Inspector] Server state changed:",r,a)},onSamplingRequest:(r,a,o,i,l)=>{const u=At(d.jsx(cTe,{requestId:r.id,serverName:o,onViewDetails:()=>{const f=new CustomEvent("navigate-to-sampling",{detail:{requestId:r.id}});window.dispatchEvent(f),At.dismiss(u)},onApprove:f=>{i(r.id,f),At.success("Sampling request approved"),At.dismiss(u)},onDeny:()=>{l(r.id,"User denied from toast"),At.dismiss(u)}}),{duration:1/0})},onElicitationRequest:(r,a,o,i,l)=>{const u=r.request.mode||"form",f=r.request.message,m=u==="url"&&"url"in r.request?r.request.url:void 0,h=At(d.jsx(cae,{requestId:r.id,serverName:o,mode:u,message:f,url:m,onViewDetails:()=>{const g=new CustomEvent("navigate-to-elicitation",{detail:{requestId:r.id}});window.dispatchEvent(g),At.dismiss(h)},onOpenUrl:u==="url"&&m?()=>{window.open(m,"_blank"),At.dismiss(h)}:void 0,onCancel:()=>{l(r.id,"User cancelled from toast"),At.dismiss(h)}}),{duration:1/0})},children:d.jsxs(P0e,{children:[d.jsx(Qpe,{basename:"/inspector",children:d.jsxs(Gfe,{children:[d.jsx(w_,{path:"/oauth/callback",element:d.jsx(ETe,{})}),d.jsx(w_,{path:"/",element:d.jsx(xTe,{children:d.jsx(j0e,{})})})]})}),d.jsx(CTe,{position:"top-center"})]})})})}const r4=new URLSearchParams(window.location.search);if(r4.has("code")||r4.has("error"))try{xN()}catch(e){console.error("[inspector] OAuth callback error:",e)}const a4=document.getElementById("root");a4?lae.createRoot(a4).render(d.jsx(RTe,{})):console.error("[inspector] Root element not found");const kTe=Object.freeze(Object.defineProperty({__proto__:null,clearRpcLogs:Uy,getAllRpcLogs:SN,getRpcLogs:kB,subscribeToRpcLogs:_N,wrapTransportForLogging:AB},Symbol.toStringTag,{value:"Module"}));export{oy as $,Ec as A,_pe as B,N_ as C,BTe as D,ws as E,uw as F,HTe as G,JN as H,Na as I,zpe as J,b_ as K,ac as L,hfe as M,ua as N,rNe as O,ofe as P,mpe as Q,wNe as R,ANe as S,pNe as T,aNe as U,Qpe as V,y6 as W,SNe as X,ql as Y,QN as Z,ze as _,Ua as a,_fe as a$,b6 as a0,yNe as a1,tNe as a2,vNe as a3,tme as a4,nNe as a5,Cde as a6,p6 as a7,w_ as a8,Nc as a9,bNe as aA,ime as aB,xNe as aC,zTe as aD,ENe as aE,ga as aF,Yy as aG,oNe as aH,x_ as aI,INe as aJ,qde as aK,FTe as aL,gm as aM,Ro as aN,sNe as aO,Gde as aP,eme as aQ,RNe as aR,JTe as aS,dC as aT,XTe as aU,Mfe as aV,CNe as aW,Pfe as aX,TNe as aY,NNe as aZ,sme as a_,Gfe as aa,Ype as ab,nme as ac,kNe as ad,GTe as ae,si as af,gl as ag,iw as ah,lf as ai,ka as aj,oo as ak,sw as al,iNe as am,dNe as an,cNe as ao,qH as ap,yC as aq,hNe as ar,XH as as,ZH as at,eC as au,gNe as av,mNe as aw,pC as ax,Et as ay,rh as az,ONe as b,nr as b$,Tc as b0,rme as b1,uC as b2,Aa as b3,KTe as b4,cC as b5,bl as b6,Lfe as b7,WTe as b8,Nfe as b9,dr as bA,de as bB,wt as bC,An as bD,b3 as bE,$Te as bF,no as bG,rr as bH,PTe as bI,MTe as bJ,fr as bK,Ep as bL,jTe as bM,pl as bN,dJ as bO,dX as bP,EX as bQ,IZ as bR,LZ as bS,uJ as bT,uX as bU,DTe as bV,NZ as bW,ol as bX,OQ as bY,ree as bZ,m3 as b_,YTe as ba,oC as bb,nh as bc,ZTe as bd,qTe as be,Cfe as bf,_Ne as bg,w6 as bh,cme as bi,Pte as bj,ITe as bk,Um as bl,qb as bm,Ure as bn,Sv as bo,rs as bp,Fe as bq,$re as br,Bre as bs,v$ as bt,OTe as bu,zre as bv,at as bw,nt as bx,er as by,eee as bz,Dpe as c,IX as c0,y4 as c1,vZ as c2,ey as c3,sZ as c4,Hre as c5,iZ as c6,xN as c7,wZ as c8,hpe as d,le as e,Mu as f,fc as g,QTe as h,eNe as i,OV as j,ppe as k,Efe as l,Uo as m,Sfe as n,ym as o,LTe as p,So as q,y as r,jpe as s,afe as t,fC as u,VTe as v,v_ as w,fNe as x,uNe as y,lNe as z};
1783
+ `),ue.document.close())}},[E]),Nn=y.useCallback(()=>{W?(he.current&&he.current.expand(),Te.current&&Te.current.expand(),re(!1)):(he.current&&he.current.collapse(),Te.current&&Te.current.collapse(),re(!0))},[W]),ot=y.useCallback(()=>{i&&(te(""),K(!0))},[i]),zn=y.useCallback(()=>{if(!i)return;const Ye={id:`${Date.now()}-${Math.random()}`,name:Z.trim()||`${i.name} - ${new Date().toLocaleString()}`,toolName:i.name,args:g,savedAt:Date.now(),serverId:i._serverId,serverName:i._serverName};dt([...L,Ye]),ra.getInstance().capture(new Fce({toolName:i.name,serverId:a})).catch(()=>{}),K(!1),te("")},[i,Z,g,L,dt,a]),qt=y.useCallback(Ye=>{dt(L.filter(We=>We.id!==Ye)),u?.id===Ye&&f(null)},[L,dt,u]);return U?d.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[$!=="list"&&d.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[d.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>{$==="response"?G("detail"):(l(null),G("list"))},className:"p-0 h-8 w-8",children:d.jsx(tw,{className:"h-4 w-4"})}),d.jsxs("div",{className:"flex items-center text-sm font-medium",children:[d.jsx("button",{onClick:()=>{l(null),G("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Tools"}),$==="detail"&&d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),d.jsx("button",{onClick:()=>{G("response")},className:$==="detail"?"text-foreground hover:underline":$==="response"?"text-muted-foreground hover:text-foreground hover:underline cursor-pointer":"text-muted-foreground",children:"Execute"})]}),$==="response"&&d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),d.jsx("span",{className:"text-foreground",children:"Response"})]})]})]}),d.jsx("div",{className:"flex-1 relative overflow-hidden",children:d.jsxs(Rw,{initial:!1,mode:"popLayout",children:[$==="list"&&d.jsxs(Fa.div,{initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 flex flex-col bg-background z-0",children:[d.jsx(GF,{activeTab:O,isSearchExpanded:F,searchQuery:A,filteredToolsCount:Ve.length,savedRequestsCount:L.length,onSearchExpand:()=>ae(!0),onSearchChange:C,onSearchBlur:Ee,onTabSwitch:()=>M(O==="tools"?"saved":"tools"),searchInputRef:H}),O==="tools"?d.jsx(VF,{tools:Ve,selectedTool:i,onToolSelect:ct,focusedIndex:ee}):d.jsx($F,{savedRequests:L,selectedRequest:u,onLoadRequest:rt,onDeleteRequest:qt,focusedIndex:ee})]},"list"),$==="detail"&&d.jsx(Fa.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-10",children:d.jsx(FF,{selectedTool:i,toolArgs:g,isExecuting:w,isConnected:o,onArgChange:Ce,onExecute:He,onSave:ot})},"detail"),$==="response"&&d.jsx(Fa.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-20",children:d.jsx(HF,{results:it,copiedResult:_,previewMode:V,serverId:a,readResource:r,onCopy:st,onDelete:Je,onFullscreen:kt,onTogglePreview:()=>Y(!V)})},"response")]})}),d.jsx(UF,{isOpen:B,requestName:Z,defaultPlaceholder:`${i?.name} - ${new Date().toLocaleString()}`,onRequestNameChange:te,onSave:zn,onCancel:()=>K(!1)})]}):d.jsxs(Ta,{direction:"horizontal",className:"h-full",children:[d.jsx(Yn,{ref:he,defaultSize:33,collapsible:!0,className:"flex flex-col h-full relative",children:d.jsxs(Ta,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[d.jsx(Yn,{defaultSize:75,minSize:30,children:d.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[d.jsx(GF,{activeTab:O,isSearchExpanded:F,searchQuery:A,filteredToolsCount:Ve.length,savedRequestsCount:L.length,onSearchExpand:()=>ae(!0),onSearchChange:C,onSearchBlur:Ee,onTabSwitch:()=>M(O==="tools"?"saved":"tools"),searchInputRef:H}),O==="tools"?d.jsx(VF,{tools:Ve,selectedTool:i,onToolSelect:ct,focusedIndex:ee}):d.jsx($F,{savedRequests:L,selectedRequest:u,onLoadRequest:rt,onDeleteRequest:qt,focusedIndex:ee})]})}),d.jsx(Ho,{withHandle:!0}),d.jsxs(Yn,{ref:$e,defaultSize:0,collapsible:!0,minSize:5,collapsedSize:5,style:{minHeight:45},onCollapse:()=>{J(!0)},onExpand:()=>{J(!1)},className:"flex flex-col border-t dark:border-zinc-700",children:[d.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:Ye=>{Ye.preventDefault(),Ye.stopPropagation(),ne?($e.current?.resize(25),J(!1)):($e.current?.resize(5),J(!0))},children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),pe>0&&d.jsx(Pr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:pe}),pe>0&&!ne&&d.jsx(Me,{variant:"ghost",size:"sm",onClick:Ye=>{Ye.preventDefault(),Ye.stopPropagation(),Ge.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:d.jsx(ni,{className:"h-3.5 w-3.5"})})]}),d.jsx(hs,{className:`h-4 w-4 text-muted-foreground transition-transform ${ne?"":"rotate-180"}`})]}),d.jsx("div",{className:`flex-1 overflow-hidden min-h-0 ${ne?"hidden":""}`,children:d.jsx(KO,{serverIds:[a],onCountChange:me,onClearRef:Ge})})]})]})}),d.jsx(Ho,{withHandle:!0}),d.jsx(Yn,{defaultSize:67,children:d.jsxs(Ta,{direction:"vertical",children:[d.jsx(Yn,{ref:Te,defaultSize:40,collapsible:!0,children:d.jsx(FF,{selectedTool:i,toolArgs:g,isExecuting:w,isConnected:o,onArgChange:Ce,onExecute:He,onSave:ot,onCancel:()=>{k&&k.abort()}})}),d.jsx(Ho,{withHandle:!0}),d.jsx(Yn,{ref:Be,defaultSize:60,children:d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(HF,{results:it,copiedResult:_,previewMode:V,serverId:a,readResource:r,onCopy:st,onDelete:Je,onFullscreen:kt,onTogglePreview:()=>Y(!V),onMaximize:Nn,isMaximized:W})})})]})}),d.jsx(UF,{isOpen:B,requestName:Z,defaultPlaceholder:`${i?.name} - ${new Date().toLocaleString()}`,onRequestNameChange:te,onSave:zn,onCancel:()=>K(!1)})]})}FW.displayName="ToolsTab";function aTe({isSearchExpanded:e,searchQuery:t,filteredRequestsCount:n,requestsCount:r,onSearchExpand:a,onSearchChange:o,onSearchBlur:i,onRejectAll:l,searchInputRef:u}){return d.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[d.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?d.jsx(Hn,{ref:u,placeholder:"Search requests...",value:t,onChange:f=>o(f.target.value),onBlur:i,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Sampling"}),d.jsx(Pr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:d.jsx(sf,{className:"h-4 w-4"})})}),d.jsxs(Yt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(xh,{children:"F"})]})]})]})}),d.jsx("div",{className:"flex items-center gap-2",children:d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:l,disabled:r===0,className:"h-8 w-8 p-0",children:d.jsx(ni,{className:"h-4 w-4"})})}),d.jsx(Yt,{side:"bottom",children:"Reject all"})]})})]})}function oTe({requests:e,selectedRequest:t,onRequestSelect:n,focusedIndex:r,formatRelativeTime:a,listRef:o}){return e.length===0?d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx(of,{vertical:!0,noBorder:!0,message:"No sampling requests"})}):d.jsx("div",{ref:o,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((i,l)=>{const u=i.request.params?.messages?.length||0,f=i.request.params?.maxTokens;return d.jsx(El,{id:`sampling-request-${i.id}`,isSelected:t?.id===i.id,isFocused:r===l,title:d.jsxs("span",{className:"flex items-center gap-3",children:[i.serverName,d.jsx("span",{className:"size-1.5 block rounded-full bg-orange-500"})]}),description:(()=>{const m=a(i.timestamp),h=[];u>0&&h.push(`${u} message${u>1?"s":""}`),f&&h.push(`max ${f} tokens`);const g=h.length>0?` | ${h.join(", ")}`:"";return m+g})(),onClick:()=>n(i)},i.id)})})}function sTe({llmConfig:e}){const t=y.useRef(null);return{generateResponse:y.useCallback(async({request:r})=>{if(!e)throw new Error("LLM config is not available");const a=r.params||{},o=a.maxTokens,i=a.temperature;a.modelPreferences;const l=a.messages||[];if(console.log("[useSamplingLLM] Request structure:",{hasParams:!!a,messagesCount:l.length,messages:l,params:a}),l.length===0)throw new Error("No messages found in sampling request");const u=[],{HumanMessage:f,AIMessage:m}=await Ua(async()=>{const{HumanMessage:E,AIMessage:x}=await import("./index-Bx2mJviJ.js").then(w=>w.bK);return{HumanMessage:E,AIMessage:x}},[]);for(const E of l){if(!E||!E.role){console.warn("Skipping invalid message:",E);continue}const x=Array.isArray(E.content)?E.content[0]:E.content;if(!x){console.warn("Skipping message with no content:",E);continue}x.type==="text"&&x.text?E.role==="user"?u.push(new f(x.text)):E.role==="assistant"&&u.push(new m(x.text)):console.warn("Skipping message with unsupported content type:",x)}if(u.length===0)throw new Error("No valid messages could be converted. Please ensure messages have 'text' content type.");if(!t.current||t.current.provider!==e.provider||t.current.model!==e.model||t.current.apiKey!==e.apiKey){let E;const x={model:e.model,apiKey:e.apiKey};if(o!==void 0&&(x.maxTokens=o),i!==void 0?x.temperature=i:e.temperature!==void 0&&(x.temperature=e.temperature),e.provider==="openai"){const{ChatOpenAI:w}=await Ua(async()=>{const{ChatOpenAI:S}=await import("./index-CR746V6H.js");return{ChatOpenAI:S}},__vite__mapDeps([0,1,2,3,4,5]));E=new w(x)}else if(e.provider==="anthropic"){const{ChatAnthropic:w}=await Ua(async()=>{const{ChatAnthropic:S}=await import("./index-C6J4X9FC.js");return{ChatAnthropic:S}},__vite__mapDeps([6,2,1,5]));E=new w(x)}else if(e.provider==="google"){const{ChatGoogleGenerativeAI:w}=await Ua(async()=>{const{ChatGoogleGenerativeAI:S}=await import("./index-BVVKUeFG.js");return{ChatGoogleGenerativeAI:S}},__vite__mapDeps([7,2,1,4]));E=new w(x)}else throw new Error(`Unsupported LLM provider: ${e.provider}`);t.current={instance:E,provider:e.provider,model:e.model,apiKey:e.apiKey}}const h=await t.current.instance.invoke(u);return{role:"assistant",content:{type:"text",text:h.content||h.text||""},model:e.model,stopReason:"endTurn"}},[e]),isAvailable:e!==null}}function iTe({request:e,onApprove:t,onReject:n,onClose:r,previewMode:a,onTogglePreview:o,isCopied:i,onCopy:l,onDownload:u,onFullscreen:f,llmConfig:m}){const[h,g]=y.useState("manual"),[b,E]=y.useState("stub-model"),[x,w]=y.useState("endTurn"),[S,_]=y.useState("assistant"),[T,k]=y.useState("text"),[R,A]=y.useState("positive"),[C,O]=y.useState(""),[M,L]=y.useState("image/png"),[j,B]=y.useState(!1),[K,Z]=y.useState(null),{generateResponse:te,isAvailable:V}=sTe({llmConfig:m});y.useEffect(()=>{e&&(E("stub-model"),w("endTurn"),_("assistant"),k("text"),A("positive"),O(""),L("image/png"),Z(null))},[e?.id]);const Y=async()=>{if(!(!e||!V)){B(!0),Z(null);try{const P=await te({request:e.request});E(P.model||m?.model||"stub-model"),w(P.stopReason||"endTurn"),_(P.role||"assistant");const H=Array.isArray(P.content)?P.content[0]:P.content;H.type==="text"?(k("text"),A(H.text||"")):H.type==="image"&&(k("image"),O(H.data||""),L(H.mimeType||"image/png"))}catch(P){const H=P instanceof Error?P.message:"Failed to generate response";Z(H),At.error("LLM Generation Failed",{description:H})}finally{B(!1)}}},F=y.useMemo(()=>{const P={model:b,stopReason:x,role:S,content:{type:T}};return T==="text"?P.content.text=R:T==="image"&&(P.content.data=C,P.content.mimeType=M),P},[b,x,S,T,R,C,M]),ae=()=>{if(!e)return;const P=fN.safeParse(F);if(!P.success){At.error("Invalid response",{description:`Validation failed: ${P.error.message}`});return}t(e.id,P.data),r(),Ua(()=>Promise.resolve().then(()=>Ec),void 0).then(H=>{const U=At(H.createElement("div",{className:"space-y-3"},H.createElement("div",null,H.createElement("strong",null,"Sampling Response Sent"),H.createElement("p",{className:"text-sm text-muted-foreground mt-1"},"The tool will continue executing.")),H.createElement("div",{className:"flex gap-2"},H.createElement("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>{const D=new globalThis.CustomEvent("navigate-to-tool-result",{detail:{toolName:e.toolName}});window.dispatchEvent(D),At.dismiss(U)}},"View Tool Result"))),{duration:5e3})})},ee=()=>{e&&(n(e.id,"User rejected sampling request"),r())};return e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:"flex items-center justify-between p-4 border-b dark:border-zinc-700",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h3",{className:"font-medium text-gray-900 dark:text-gray-100",children:e.serverName}),d.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleString()})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:l,className:"h-8 w-8 p-0",children:i?d.jsx(Or,{className:"h-4 w-4 text-green-600"}):d.jsx(wr,{className:"h-4 w-4"})})}),d.jsx(Yt,{children:"Copy request"})]}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",children:d.jsx(th,{className:"h-4 w-4"})})}),d.jsx(Yt,{children:"Download request"})]}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:f,className:"h-8 w-8 p-0",children:d.jsx(qN,{className:"h-4 w-4"})})}),d.jsx(Yt,{children:"Fullscreen"})]}),d.jsx(Me,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:d.jsx(vs,{className:"h-4 w-4"})})]})]}),d.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[d.jsxs("div",{className:"space-y-2",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Request"}),d.jsx("div",{className:"bg-muted rounded-lg p-3 max-h-64 overflow-auto",children:d.jsx(yr,{data:e.request})})]}),d.jsxs("div",{className:"space-y-4",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Response"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx(wn,{htmlFor:`responseMode-${e.id}`,className:"text-xs text-gray-500 dark:text-gray-400",children:"Mode:"}),d.jsxs(Zs,{value:h,onValueChange:P=>g(P),children:[d.jsx(Xs,{id:`responseMode-${e.id}`,className:"w-32 h-8 text-xs",children:d.jsx(qs,{})}),d.jsxs(Js,{children:[d.jsx(fa,{value:"manual",children:"Manual"}),d.jsx(fa,{value:"llm",children:"LLM"})]})]})]})]}),h==="llm"&&d.jsxs("div",{className:"space-y-2 p-3 bg-muted rounded-lg",children:[V?d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx(Me,{onClick:Y,disabled:j,size:"sm",className:"flex items-center gap-2",children:j?d.jsxs(d.Fragment,{children:[d.jsx(cl,{className:"h-4 w-4 animate-spin"}),"Generating..."]}):d.jsxs(d.Fragment,{children:[d.jsx(pde,{className:"h-4 w-4"}),"Generate with LLM"]})}),d.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["Using ",m?.provider," (",m?.model,")"]})]}):d.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:"LLM not configured. Please configure LLM in the Chat tab."}),K&&d.jsx("div",{className:"text-xs text-red-600 dark:text-red-400",children:K})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(wn,{htmlFor:`model-${e.id}`,children:"Model"}),d.jsx(Hn,{id:`model-${e.id}`,value:b,onChange:P=>E(P.target.value),placeholder:"stub-model",disabled:h==="llm"&&j})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(wn,{htmlFor:`stopReason-${e.id}`,children:"Stop Reason"}),d.jsx(Hn,{id:`stopReason-${e.id}`,value:x,onChange:P=>w(P.target.value),placeholder:"endTurn",disabled:h==="llm"&&j})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(wn,{htmlFor:`role-${e.id}`,children:"Role"}),d.jsxs(Zs,{value:S,onValueChange:P=>_(P),disabled:h==="llm"&&j,children:[d.jsx(Xs,{id:`role-${e.id}`,children:d.jsx(qs,{})}),d.jsxs(Js,{children:[d.jsx(fa,{value:"assistant",children:"assistant"}),d.jsx(fa,{value:"user",children:"user"})]})]})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(wn,{htmlFor:`contentType-${e.id}`,children:"Content Type"}),d.jsxs(Zs,{value:T,onValueChange:P=>k(P),disabled:h==="llm"&&j,children:[d.jsx(Xs,{id:`contentType-${e.id}`,children:d.jsx(qs,{})}),d.jsxs(Js,{children:[d.jsx(fa,{value:"text",children:"text"}),d.jsx(fa,{value:"image",children:"image"})]})]})]}),T==="text"&&d.jsxs("div",{className:"space-y-2",children:[d.jsx(wn,{htmlFor:`text-${e.id}`,children:"Text Content"}),d.jsx(bc,{id:`text-${e.id}`,value:R,onChange:P=>A(P.target.value),placeholder:"Enter response text...",rows:6,disabled:h==="llm"&&j})]}),T==="image"&&d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"space-y-2",children:[d.jsx(wn,{htmlFor:`imageData-${e.id}`,children:"Base64 Image Data"}),d.jsx(bc,{id:`imageData-${e.id}`,value:C,onChange:P=>O(P.target.value),placeholder:"Base64 encoded image data...",rows:4,disabled:h==="llm"&&j})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(wn,{htmlFor:`mimeType-${e.id}`,children:"MIME Type"}),d.jsx(Hn,{id:`mimeType-${e.id}`,value:M,onChange:P=>L(P.target.value),placeholder:"image/png",disabled:h==="llm"&&j})]})]})]})]}),d.jsxs("div",{className:"flex gap-2 p-4 border-t dark:border-zinc-700",children:[d.jsx(Me,{onClick:ae,className:"flex-1",disabled:h==="llm"&&j,children:"Approve"}),d.jsx(Me,{onClick:ee,variant:"outline",className:"flex-1",disabled:h==="llm"&&j,children:"Reject"})]})]}):d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select a sampling request to view details"})})}const lTe={model:"stub-model",stopReason:"endTurn",role:"assistant",content:{type:"text",text:"positive"}};function cTe({requestId:e,serverName:t,onViewDetails:n,onApprove:r,onDeny:a}){return d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{children:[d.jsx("strong",{children:"Sampling Request Received"}),d.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["New request from ",t]})]}),d.jsxs("div",{className:"flex gap-2",children:[d.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:o=>{o.stopPropagation(),n()},children:"View Details"}),d.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:o=>{o.stopPropagation(),r(lTe)},children:"Approve"}),d.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:o=>{o.stopPropagation(),a()},children:"Deny"})]})]})}function uTe({pendingRequests:e,onApprove:t,onReject:n,serverId:r,isConnected:a,mcpServerUrl:o}){const{selectedSamplingRequestId:i,setSelectedSamplingRequestId:l}=kc(),{llmConfig:u}=mW({mcpServerUrl:o}),[f,m]=y.useState(null),[h,g]=y.useState(""),[b,E]=y.useState(-1),[x,w]=y.useState(!0),[S,_]=y.useState(!1),[T,k]=y.useState(!0),[R,A]=y.useState(!1),C=y.useRef(null),O=y.useRef(null),M=y.useRef(null),L=y.useRef(!1);y.useEffect(()=>{if(console.log("[SamplingTab] Auto-selection check:",{selectedSamplingRequestId:i,pendingRequestsCount:e.length,currentSelectedId:f?.id}),i&&e.length>0){const F=e.find(ae=>ae.id===i);console.log("[SamplingTab] Found request for auto-selection:",!!F,F?.id),F&&(console.log("[SamplingTab] Auto-selecting request:",F.id),l(null),m(F),setTimeout(()=>{const ae=document.getElementById(`sampling-request-${F.id}`);console.log("[SamplingTab] Scrolling to element:",!!ae),ae&&ae.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[i,e,l]),y.useEffect(()=>{const F=ae=>{const P=ae.detail.requestId;console.log("[SamplingTab] Custom navigate event received:",P);const H=e.find(U=>U.id===P);H&&(console.log("[SamplingTab] Selecting request from event:",P),m(H),setTimeout(()=>{const U=document.getElementById(`sampling-request-${P}`);U&&U.scrollIntoView({behavior:"smooth",block:"nearest"})},200))};return window.addEventListener("navigate-to-sampling",F),()=>window.removeEventListener("navigate-to-sampling",F)},[e]),y.useEffect(()=>{x&&e.length>0&&C.current&&!L.current&&(C.current.scrollTop=0)},[e.length,x]),y.useEffect(()=>{const F=C.current;if(!F)return;const ae=()=>{F.scrollTop>0&&(L.current=!0,w(!1))};return F.addEventListener("scroll",ae),()=>F.removeEventListener("scroll",ae)},[]),y.useEffect(()=>{e.length===0&&(L.current=!1,w(!0))},[e.length]),y.useEffect(()=>{S&&M.current&&M.current.focus()},[S]);const j=y.useCallback(()=>{h.trim()||_(!1)},[h]),B=y.useMemo(()=>{if(!h.trim())return e;const F=h.toLowerCase();return e.filter(ae=>ae.serverName.toLowerCase().includes(F)||JSON.stringify(ae.request||{}).toLowerCase().includes(F))},[e,h]);y.useEffect(()=>{E(-1)},[h]),y.useEffect(()=>{const F=ae=>{const ee=ae.target;if(ee.tagName==="INPUT"||ee.tagName==="TEXTAREA"||ee.contentEditable==="true"||ae.metaKey||ae.ctrlKey||ae.altKey)return;const H=B;if(ae.key==="ArrowDown")ae.preventDefault(),E(U=>{const D=U+1;return D>=H.length?0:D});else if(ae.key==="ArrowUp")ae.preventDefault(),E(U=>{const D=U-1;return D<0?H.length-1:D});else if(ae.key==="Enter"&&b>=0){ae.preventDefault();const U=B[b];U&&K(U)}};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[b,B]),y.useEffect(()=>{if(b>=0){const F=`sampling-request-${B[b]?.id}`,ae=document.getElementById(F);ae&&ae.scrollIntoView({behavior:"smooth",block:"nearest"})}},[b,B]);const K=y.useCallback(F=>{m(F)},[]),Z=y.useCallback(()=>{window.confirm("Are you sure you want to reject all sampling requests? This cannot be undone.")&&(e.forEach(F=>{n(F.id,"User rejected all requests")}),m(null))},[e,n]),te=y.useCallback(async()=>{if(f)try{await navigator.clipboard.writeText(JSON.stringify({id:f.id,serverName:f.serverName,timestamp:f.timestamp,request:f.request},null,2)),A(!0),setTimeout(()=>A(!1),2e3)}catch(F){console.error("[SamplingTab] Failed to copy request:",F)}},[f]),V=y.useCallback(()=>{if(f)try{const F=new globalThis.Blob([JSON.stringify({id:f.id,serverName:f.serverName,timestamp:f.timestamp,request:f.request},null,2)],{type:"application/json"}),ae=URL.createObjectURL(F),ee=document.createElement("a");ee.href=ae,ee.download=`sampling-request-${Date.now()}.json`,document.body.appendChild(ee),ee.click(),document.body.removeChild(ee),URL.revokeObjectURL(ae)}catch(F){console.error("[SamplingTab] Failed to download request:",F)}},[f]),Y=y.useCallback(async()=>{if(O.current)try{document.fullscreenElement?await document.exitFullscreen():await O.current.requestFullscreen()}catch(F){console.error("[SamplingTab] Failed to toggle fullscreen:",F)}},[]);return a?d.jsxs(Ta,{direction:"horizontal",className:"h-full",children:[d.jsx(Yn,{defaultSize:40,minSize:30,children:d.jsx(Ta,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:d.jsxs(Yn,{defaultSize:75,minSize:30,children:[d.jsx(aTe,{isSearchExpanded:S,searchQuery:h,filteredRequestsCount:B.length,requestsCount:e.length,onSearchExpand:()=>_(!0),onSearchChange:g,onSearchBlur:j,onRejectAll:Z,searchInputRef:M}),d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(oTe,{requests:B,selectedRequest:f,onRequestSelect:K,focusedIndex:b,formatRelativeTime:Ev,listRef:C})})]})})}),d.jsx(Ho,{}),d.jsx(Yn,{defaultSize:60,minSize:40,children:d.jsx("div",{ref:O,className:"h-full bg-white dark:bg-zinc-900",children:d.jsx(iTe,{request:f,onApprove:t,onReject:n,onClose:()=>m(null),previewMode:T,onTogglePreview:()=>k(!T),isCopied:R,onCopy:te,onDownload:V,onFullscreen:Y,llmConfig:u})})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(BH,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function dTe({isSearchExpanded:e,searchQuery:t,filteredRequestsCount:n,requestsCount:r,onSearchExpand:a,onSearchChange:o,onSearchBlur:i,onCancelAll:l,searchInputRef:u}){return d.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[d.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?d.jsx(Hn,{ref:u,placeholder:"Search requests...",value:t,onChange:f=>o(f.target.value),onBlur:i,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Elicitation"}),d.jsx(Pr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:d.jsx(sf,{className:"h-4 w-4"})})}),d.jsxs(Yt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(xh,{children:"F"})]})]})]})}),d.jsx("div",{className:"flex items-center gap-2",children:d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:l,disabled:r===0,className:"h-8 w-8 p-0",children:d.jsx(vs,{className:"h-4 w-4"})})}),d.jsx(Yt,{side:"bottom",children:"Cancel all"})]})})]})}function fTe({requests:e,selectedRequest:t,onRequestSelect:n,focusedIndex:r,formatRelativeTime:a,listRef:o}){return e.length===0?d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx(of,{vertical:!0,noBorder:!0,message:"No elicitation requests"})}):d.jsx("div",{ref:o,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((i,l)=>{const u=i.request.mode||"form",f=u==="form"&&"requestedSchema"in i.request&&i.request.requestedSchema;return d.jsx(El,{id:`elicitation-request-${i.id}`,isSelected:t?.id===i.id,isFocused:r===l,title:d.jsxs("span",{className:"flex items-center gap-3",children:[i.serverName,d.jsx(Pr,{variant:"outline",className:u==="url"?"bg-blue-500/20 text-blue-600 dark:text-blue-400 border-blue-500/50":"bg-green-500/20 text-green-600 dark:text-green-400 border-green-500/50",children:u})]}),description:(()=>{const m=a(i.timestamp),h=[];f&&h.push("with schema"),u==="url"&&h.push("external action");const g=h.length>0?` | ${h.join(", ")}`:"";return m+g})(),onClick:()=>n(i)},i.id)})})}function pTe({request:e,onApprove:t,onReject:n,onClose:r,previewMode:a,onTogglePreview:o,isCopied:i,onCopy:l,onDownload:u,onFullscreen:f}){const[m,h]=y.useState({}),[g,b]=y.useState(!1),E=e?.request.mode||"form",x=E==="form",w=E==="url";y.useEffect(()=>{if(e&&x&&"requestedSchema"in e.request){const C=e.request.requestedSchema,O={};if(C?.type==="object"&&C.properties)for(const[M,L]of Object.entries(C.properties)){const j=L;j.default!==void 0?O[M]=j.default:j.type==="boolean"?O[M]=!1:j.type==="number"||j.type==="integer"?O[M]=0:O[M]=""}h(O)}b(!1)},[e?.id,x]);const S=(C,O)=>{h(M=>({...M,[C]:O}))},_=()=>{if(e){if(x){if("requestedSchema"in e.request){const C=e.request.requestedSchema;if(C?.required){const O=C.required.filter(M=>m[M]===void 0||m[M]===""||m[M]===null);if(O.length>0){At.error("Missing required fields",{description:`Please fill in: ${O.join(", ")}`});return}}}t(e.id,{action:"accept",data:m})}else w&&t(e.id,{action:"accept"});r(),Ua(()=>Promise.resolve().then(()=>Ec),void 0).then(C=>{const O=At(C.createElement("div",{className:"space-y-3"},C.createElement("div",null,C.createElement("strong",null,"Elicitation Response Sent"),C.createElement("p",{className:"text-sm text-muted-foreground mt-1"},"The tool will continue executing.")),C.createElement("div",{className:"flex gap-2"},C.createElement("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>{const M=new globalThis.CustomEvent("navigate-to-tool-result",{detail:{toolName:null}});window.dispatchEvent(M),At.dismiss(O)}},"View Tool Result"))),{duration:5e3})})}},T=()=>{e&&(t(e.id,{action:"decline"}),r())},k=()=>{e&&(n(e.id,"User cancelled elicitation request"),r())},R=()=>{e&&w&&"url"in e.request&&(window.open(e.request.url,"_blank"),b(!0))},A=y.useMemo(()=>{if(!e||!x||!("requestedSchema"in e.request))return null;const C=e.request.requestedSchema;if(!C||C.type!=="object"||!C.properties)return d.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"No form schema available"});const O=C.properties,M=C.required||[];return d.jsx("div",{className:"space-y-4",children:Object.entries(O).map(([L,j])=>{const B=j,K=M.includes(L),Z=B.type||"string",te=B.title||L,V=B.description;return d.jsxs("div",{className:"space-y-2",children:[d.jsxs(wn,{htmlFor:`field-${L}`,children:[te,K&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),V&&d.jsx("p",{className:"text-xs text-muted-foreground",children:V}),Z==="boolean"?d.jsxs("div",{className:"flex items-center space-x-2",children:[d.jsx(Mm,{id:`field-${L}`,checked:m[L]||!1,onCheckedChange:Y=>S(L,Y)}),d.jsx(wn,{htmlFor:`field-${L}`,className:"text-sm font-normal cursor-pointer",children:B.title||L})]}):Z==="number"||Z==="integer"?d.jsx(Hn,{id:`field-${L}`,type:"number",value:m[L]||"",onChange:Y=>S(L,Z==="integer"?parseInt(Y.target.value,10):parseFloat(Y.target.value)),placeholder:B.default?.toString()||""}):B.enum?d.jsxs("select",{id:`field-${L}`,value:m[L]||"",onChange:Y=>S(L,Y.target.value),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:[d.jsx("option",{value:"",children:"Select..."}),B.enum.map(Y=>d.jsx("option",{value:Y,children:Y},Y))]}):Z==="string"&&(B.format==="textarea"||B.maxLength>100)?d.jsx(bc,{id:`field-${L}`,value:m[L]||"",onChange:Y=>S(L,Y.target.value),placeholder:B.default||"",rows:4}):d.jsx(Hn,{id:`field-${L}`,type:"text",value:m[L]||"",onChange:Y=>S(L,Y.target.value),placeholder:B.default||""})]},L)})})},[e,m,x]);return e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:"flex items-center justify-between p-4 border-b dark:border-zinc-700",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h3",{className:"font-medium text-gray-900 dark:text-gray-100",children:e.serverName}),d.jsx(Pr,{variant:"outline",className:w?"bg-blue-500/20 text-blue-600 dark:text-blue-400 border-blue-500/50":"bg-green-500/20 text-green-600 dark:text-green-400 border-green-500/50",children:E}),d.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleString()})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:l,className:"h-8 w-8 p-0",children:i?d.jsx(Or,{className:"h-4 w-4 text-green-600"}):d.jsx(wr,{className:"h-4 w-4"})})}),d.jsx(Yt,{children:"Copy request"})]}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",children:d.jsx(th,{className:"h-4 w-4"})})}),d.jsx(Yt,{children:"Download request"})]}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",onClick:f,className:"h-8 w-8 p-0",children:d.jsx(qN,{className:"h-4 w-4"})})}),d.jsx(Yt,{children:"Fullscreen"})]}),d.jsx(Me,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:d.jsx(vs,{className:"h-4 w-4"})})]})]}),d.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[d.jsxs("div",{className:"space-y-2",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Message"}),d.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:e.request.message})]}),w&&"url"in e.request&&d.jsxs("div",{className:"space-y-2",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"External Action Required"}),d.jsxs("div",{className:"bg-muted rounded-lg p-4 space-y-3",children:[d.jsx("p",{className:"text-sm text-muted-foreground",children:"This request requires you to complete an action at an external URL:"}),d.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background rounded border",children:[d.jsx("code",{className:"flex-1 text-xs font-mono break-all",children:e.request.url}),d.jsxs(Me,{size:"sm",variant:"outline",onClick:R,className:"flex items-center gap-2",children:[d.jsx(u_,{className:"h-4 w-4"}),"Open URL"]})]}),d.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[d.jsx(Mm,{id:"url-completed",checked:g,onCheckedChange:C=>b(!!C)}),d.jsx(wn,{htmlFor:"url-completed",className:"text-sm font-normal cursor-pointer",children:"I have completed the required action"})]})]})]}),x&&d.jsxs("div",{className:"space-y-2",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Form Data"}),A]}),x&&"requestedSchema"in e.request&&e.request.requestedSchema&&d.jsxs("details",{className:"space-y-2",children:[d.jsx("summary",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100 cursor-pointer",children:"Schema (for reference)"}),d.jsx("div",{className:"bg-muted rounded-lg p-3 max-h-64 overflow-auto",children:d.jsx(yr,{data:e.request.requestedSchema})})]})]}),d.jsxs("div",{className:"flex gap-2 p-4 border-t dark:border-zinc-700",children:[d.jsx(Me,{onClick:_,className:"flex-1",children:"Accept"}),d.jsx(Me,{onClick:T,variant:"outline",className:"flex-1",children:"Decline"}),d.jsx(Me,{onClick:k,variant:"outline",className:"flex-1",children:"Cancel"})]})]}):d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select an elicitation request to view details"})})}function mTe({pendingRequests:e=[],onApprove:t,onReject:n,serverId:r,isConnected:a}){const{selectedElicitationRequestId:o,setSelectedElicitationRequestId:i}=kc(),[l,u]=y.useState(null),[f,m]=y.useState(""),[h,g]=y.useState(-1),[b,E]=y.useState(!0),[x,w]=y.useState(!1),[S,_]=y.useState(!0),[T,k]=y.useState(!1),R=y.useRef(null),A=y.useRef(null),C=y.useRef(null),O=y.useRef(!1);y.useEffect(()=>{if(console.log("[ElicitationTab] Auto-selection check:",{selectedElicitationRequestId:o,pendingRequestsCount:e.length,currentSelectedId:l?.id}),o&&e.length>0){const V=e.find(Y=>Y.id===o);console.log("[ElicitationTab] Found request for auto-selection:",!!V,V?.id),V&&(console.log("[ElicitationTab] Auto-selecting request:",V.id),i(null),u(V),setTimeout(()=>{const Y=document.getElementById(`elicitation-request-${V.id}`);console.log("[ElicitationTab] Scrolling to element:",!!Y),Y&&Y.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[o,e,i]),y.useEffect(()=>{const V=Y=>{const ae=Y.detail.requestId;console.log("[ElicitationTab] Custom navigate event received:",ae);const ee=e.find(P=>P.id===ae);ee&&(console.log("[ElicitationTab] Selecting request from event:",ae),u(ee),setTimeout(()=>{const P=document.getElementById(`elicitation-request-${ae}`);P&&P.scrollIntoView({behavior:"smooth",block:"nearest"})},200))};return window.addEventListener("navigate-to-elicitation",V),()=>window.removeEventListener("navigate-to-elicitation",V)},[e]),y.useEffect(()=>{b&&e.length>0&&R.current&&!O.current&&(R.current.scrollTop=0)},[e.length,b]),y.useEffect(()=>{const V=R.current;if(!V)return;const Y=()=>{V.scrollTop>0&&(O.current=!0,E(!1))};return V.addEventListener("scroll",Y),()=>V.removeEventListener("scroll",Y)},[]),y.useEffect(()=>{e.length===0&&(O.current=!1,E(!0))},[e.length]),y.useEffect(()=>{x&&C.current&&C.current.focus()},[x]);const M=y.useCallback(()=>{f.trim()||w(!1)},[f]),L=y.useMemo(()=>{if(!f.trim())return e;const V=f.toLowerCase();return e.filter(Y=>Y.serverName.toLowerCase().includes(V)||Y.request.message.toLowerCase().includes(V)||JSON.stringify(Y.request||{}).toLowerCase().includes(V))},[e,f]);y.useEffect(()=>{g(-1)},[f]),y.useEffect(()=>{const V=Y=>{const F=Y.target;if(F.tagName==="INPUT"||F.tagName==="TEXTAREA"||F.contentEditable==="true"||Y.metaKey||Y.ctrlKey||Y.altKey)return;const ee=L;if(Y.key==="ArrowDown")Y.preventDefault(),g(P=>{const H=P+1;return H>=ee.length?0:H});else if(Y.key==="ArrowUp")Y.preventDefault(),g(P=>{const H=P-1;return H<0?ee.length-1:H});else if(Y.key==="Enter"&&h>=0){Y.preventDefault();const P=L[h];P&&j(P)}};return document.addEventListener("keydown",V),()=>document.removeEventListener("keydown",V)},[h,L]),y.useEffect(()=>{if(h>=0){const V=`elicitation-request-${L[h]?.id}`,Y=document.getElementById(V);Y&&Y.scrollIntoView({behavior:"smooth",block:"nearest"})}},[h,L]);const j=y.useCallback(V=>{u(V)},[]),B=y.useCallback(()=>{window.confirm("Are you sure you want to cancel all elicitation requests? This cannot be undone.")&&(e.forEach(V=>{n(V.id,"User cancelled all requests")}),u(null))},[e,n]),K=y.useCallback(async()=>{if(l)try{await navigator.clipboard.writeText(JSON.stringify({id:l.id,serverName:l.serverName,timestamp:l.timestamp,request:l.request},null,2)),k(!0),setTimeout(()=>k(!1),2e3)}catch(V){console.error("[ElicitationTab] Failed to copy request:",V)}},[l]),Z=y.useCallback(()=>{if(l)try{const V=new globalThis.Blob([JSON.stringify({id:l.id,serverName:l.serverName,timestamp:l.timestamp,request:l.request},null,2)],{type:"application/json"}),Y=URL.createObjectURL(V),F=document.createElement("a");F.href=Y,F.download=`elicitation-request-${Date.now()}.json`,document.body.appendChild(F),F.click(),document.body.removeChild(F),URL.revokeObjectURL(Y)}catch(V){console.error("[ElicitationTab] Failed to download request:",V)}},[l]),te=y.useCallback(async()=>{if(A.current)try{document.fullscreenElement?await document.exitFullscreen():await A.current.requestFullscreen()}catch(V){console.error("[ElicitationTab] Failed to toggle fullscreen:",V)}},[]);return a?d.jsxs(Ta,{direction:"horizontal",className:"h-full",children:[d.jsx(Yn,{defaultSize:40,minSize:30,children:d.jsx(Ta,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:d.jsxs(Yn,{defaultSize:75,minSize:30,children:[d.jsx(dTe,{isSearchExpanded:x,searchQuery:f,filteredRequestsCount:L.length,requestsCount:e.length,onSearchExpand:()=>w(!0),onSearchChange:m,onSearchBlur:M,onCancelAll:B,searchInputRef:C}),d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(fTe,{requests:L,selectedRequest:l,onRequestSelect:j,focusedIndex:h,formatRelativeTime:Ev,listRef:R})})]})})}),d.jsx(Ho,{}),d.jsx(Yn,{defaultSize:60,minSize:40,children:d.jsx("div",{ref:A,className:"h-full bg-white dark:bg-zinc-900",children:d.jsx(pTe,{request:l,onApprove:t,onReject:n,onClose:()=>u(null),previewMode:S,onTogglePreview:()=>_(!S),isCopied:T,onCopy:K,onDownload:Z,onFullscreen:te})})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(KH,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function hTe({selectedServer:e,activeTab:t,toolsSearchRef:n,promptsSearchRef:r,resourcesSearchRef:a,children:o}){return e?d.jsxs(d.Fragment,{children:[d.jsx("div",{style:{display:t==="tools"?"block":"none"},className:"h-full",children:d.jsx(FW,{ref:n,tools:e.tools,callTool:e.callTool,readResource:e.readResource,serverId:e.id,isConnected:e.state==="ready"})}),d.jsx("div",{style:{display:t==="prompts"?"block":"none"},className:"h-full",children:d.jsx(PW,{ref:r,prompts:e.prompts,callPrompt:e.getPrompt,serverId:e.id,isConnected:e.state==="ready"})}),d.jsx("div",{style:{display:t==="resources"?"block":"none"},className:"h-full",children:d.jsx(UW,{ref:a,resources:e.resources,readResource:e.readResource,serverId:e.id,isConnected:e.state==="ready"})}),d.jsx("div",{style:{display:t==="chat"?"block":"none"},className:"h-full",children:d.jsx(u_e,{connection:e,isConnected:e.state==="ready",readResource:e.readResource},e.id)}),d.jsx("div",{style:{display:t==="sampling"?"block":"none"},className:"h-full",children:d.jsx(uTe,{pendingRequests:e.pendingSamplingRequests,onApprove:e.approveSampling,onReject:e.rejectSampling,serverId:e.id,isConnected:e.state==="ready",mcpServerUrl:e.url})}),d.jsx("div",{style:{display:t==="elicitation"?"block":"none"},className:"h-full",children:d.jsx(mTe,{pendingRequests:e.pendingElicitationRequests,onApprove:e.approveElicitation,onReject:e.rejectElicitation,serverId:e.id,isConnected:e.state==="ready"})}),d.jsx("div",{style:{display:t==="notifications"?"block":"none"},className:"h-full",children:d.jsx(B_e,{notifications:e.notifications,unreadCount:e.unreadNotificationCount,markNotificationRead:e.markNotificationRead,markAllNotificationsRead:e.markAllNotificationsRead,clearNotifications:e.clearNotifications,serverId:e.id,isConnected:e.state==="ready"})}),t!=="tools"&&t!=="prompts"&&t!=="resources"&&t!=="chat"&&t!=="sampling"&&t!=="elicitation"&&t!=="notifications"&&d.jsx(d.Fragment,{children:o})]}):d.jsx(d.Fragment,{children:o})}function KF({className:e}){return d.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentcolor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[d.jsx("path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"}),d.jsx("path",{d:"M9 18c-4.51 2-5-2-7-2"})]})}const BW=y.createContext(void 0);function HW(){const e=y.use(BW);if(!e)throw new Error("useTabs must be used within a TabsProvider");return e}const VW=y.createContext(void 0);function gTe(){return y.use(VW)}function $T({ref:e,children:t,defaultValue:n,value:r,onValueChange:a,className:o,collapsed:i,onCollapsedChange:l,...u}){const[f,m]=y.useState(n||""),h=r!==void 0,g=i!==void 0,[b,E]=y.useState(!1),x=y.useCallback(T=>{h||m(T),a?.(T)},[h,a]),w=h?r:f,S=g?i:b,_=y.useCallback(T=>{g||E(T),l?.(T)},[g,l]);return d.jsx(BW,{value:{activeValue:w,handleValueChange:x,collapsed:S,handleCollapsedChange:_},children:d.jsx("div",{ref:e,className:Ue("flex flex-col gap-2",o),...u,children:t})})}$T.displayName="Tabs";function UT({ref:e,children:t,className:n,variant:r="default",collapsible:a=!1,...o}){const{activeValue:i,collapsed:l,handleCollapsedChange:u}=HW(),[f,m]=y.useState({width:0,left:0}),h=y.useRef(null),g=y.useRef(null),b=y.useRef(null),E=y.useCallback(()=>{const S=h.current;if(!S)return;const _=S.querySelector("div:first-child");if(!_)return;const T=_.querySelector(`button[data-tab-value="${i}"]`);if(T&&i){const k=_.getBoundingClientRect(),R=T.getBoundingClientRect();m({width:R.width,left:R.left-k.left})}else m({width:0,left:0})},[i]),x=y.useCallback(()=>{b.current&&clearTimeout(b.current),b.current=setTimeout(E,16)},[E]);y.useEffect(()=>{const S=setTimeout(E,10);return()=>clearTimeout(S)},[E,l]),y.useEffect(()=>{const S=h.current;if(!S)return;g.current=new ResizeObserver(()=>{x()}),g.current.observe(S);const _=S.querySelector("div:first-child");return _&&_.querySelectorAll("button[data-tab-value]").forEach(k=>{g.current&&g.current.observe(k)}),()=>{g.current&&g.current.disconnect(),b.current&&clearTimeout(b.current)}},[x]),y.useEffect(()=>{const S=()=>{x()};return window.addEventListener("resize",S),()=>window.removeEventListener("resize",S)},[x]);const w=y.useRef(null);return y.useEffect(()=>{w.current&&(w.current.style.width=`${f.width}px`,w.current.style.left=`${f.left}px`)},[f]),d.jsx(VW,{value:{variant:r,collapsed:l,handleCollapsedChange:u},children:d.jsx("div",{ref:h,className:Ue("relative flex items-center bg-none gap-1",r==="default"&&"p-1 rounded-full border border-zinc-300 dark:border-zinc-600",r==="underline"&&"border-b border-zinc-200 dark:border-zinc-700",n),...o,children:d.jsxs("div",{role:"tablist",className:"flex-1 flex items-center relative",children:[t,d.jsx("span",{ref:w,className:Ue("absolute transition-all duration-500 ease-in-out z-0",r==="default"&&"bg-white dark:bg-zinc-700 rounded-full h-[calc(100%)] top-0 border border-zinc-300 dark:border-zinc-600",r==="underline"&&"bottom-0 h-0.5 bg-black dark:bg-white")})]})})})}UT.displayName="TabsList";const bTe=({children:e,title:t,collapsed:n})=>!t||!n?e:d.jsx(WN,{children:d.jsxs(Wt,{children:[d.jsx(Kt,{children:e}),d.jsx(Yt,{children:t})]})}),zT=y.forwardRef(({children:e,value:t,className:n,disabled:r,icon:a,title:o,showDot:i=!1,...l},u)=>{const{activeValue:f,handleValueChange:m,collapsed:h}=HW(),b=gTe()?.variant||"default",E=f===t,x=h&&o?o:void 0;return d.jsx(bTe,{title:o,collapsed:h,children:d.jsxs("button",{ref:u,disabled:r,onClick:()=>m(t),"data-tab-value":t,"data-tab-active":E,role:"tab","aria-selected":E?"true":"false",title:x,className:Ue("relative z-10 flex-1 inline-flex items-center justify-center whitespace-nowrap text-sm font-medium ring-offset-background transition-all duration-500 ease-in-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 cursor-pointer",b==="default"&&"py-2.5",b==="default"&&"rounded-md px-4",b==="underline"&&"px-6 py-3 border-b-2 border-transparent",E&&"text-foreground",!E&&"text-muted-foreground hover:text-foreground",n),...l,children:[a&&d.jsx(a,{className:Ue("h-4 w-4 transition-all duration-500 ease-in-out",!h&&"mr-2",h&&"mr-0!")}),i&&d.jsx("span",{className:"absolute top-1.5 right-1.5 w-2 h-2 bg-orange-500 dark:bg-orange-400 border-2 border-white dark:border-zinc-900 rounded-full transition-opacity duration-300 z-10 animate-status-pulse-orange"}),d.jsx("span",{className:Ue("transition-all duration-500 ease-in-out overflow-hidden",h?"w-0 opacity-0":"w-auto opacity-100"),children:e})]})})});zT.displayName="TabsTrigger";function YF({serverConfig:e,additionalItems:t=[],showClients:n={cursor:!0,vsCode:!0,claudeDesktop:!0,claudeCode:!0,geminiCli:!0,codexCli:!0},className:r="",onSuccess:a,onError:o,trigger:i}){const[l,u]=y.useState(!1),[f,m]=y.useState(null),[h,g]=y.useState(!1),{url:b,name:E,headers:x}=e,w=()=>{try{const L=jG(b,E,x);window.location.href=L,a?.("Cursor")}catch(L){console.error("Failed to generate Cursor deep link:",L),o?.(L)}},S=()=>{try{const L=PG(b,E,x);window.location.href=L,a?.("VS Code")}catch(L){console.error("Failed to generate VS Code deep link:",L),o?.(L)}},_=()=>{try{$G(b,E,x),a?.("Claude Desktop")}catch(L){console.error("Failed to download .mcpb file:",L),o?.(L)}},T=()=>{m("claude-code"),u(!0)},k=()=>{m("gemini-cli"),u(!0)},R=()=>{m("codex-cli"),u(!0)},A=async L=>{try{await navigator.clipboard.writeText(L),g(!0),setTimeout(()=>g(!1),2e3)}catch(j){console.error("Failed to copy:",j),o?.(j)}},C=()=>{if(f==="claude-code"){const{command:L,envVars:j}=UG(b,E,x),B=P2(j);return d.jsxs(d.Fragment,{children:[d.jsxs(ls,{children:[d.jsx(cs,{children:"Add to Claude Code"}),d.jsx(Fp,{children:"Execute the following command in your shell to add this server to Claude Code."})]}),d.jsxs("div",{className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Instructions"}),d.jsxs("ol",{className:"space-y-2 text-xs text-muted-foreground",children:[d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"1."}),d.jsx("span",{children:"Ensure the Claude Code executable is available in your path"})]}),d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"2."}),d.jsx("span",{children:"Execute the following snippet in your shell:"})]})]})]}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"absolute top-2 right-2 z-10",children:d.jsx(Me,{variant:"ghost",size:"sm",className:"h-7 px-2 bg-background hover:bg-accent border border-border",onClick:()=>A(L),children:h?d.jsx(Or,{className:"size-3.5 text-green-600"}):d.jsx(wr,{className:"size-3.5"})})}),d.jsx("pre",{className:"bg-muted p-3 pr-14 rounded-md text-xs overflow-x-auto",children:d.jsx("code",{children:L})})]}),B&&d.jsxs("div",{children:[d.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Environment Variables"}),d.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"After installation, set these environment variables in your shell:"}),d.jsx("pre",{className:"bg-muted p-3 rounded-md text-xs overflow-x-auto",children:d.jsx("code",{children:B})})]}),d.jsxs("p",{className:"text-xs text-muted-foreground",children:["The MCP configuration supports environment variable expansion using ",d.jsx("code",{className:"text-foreground",children:"${VAR}"})," ","syntax."]})]})]})}if(f==="gemini-cli"){const{command:L,envVars:j}=zG(b,E,x),B=P2(j);return d.jsxs(d.Fragment,{children:[d.jsxs(ls,{children:[d.jsx(cs,{children:"Add to Gemini CLI"}),d.jsx(Fp,{children:"Execute the following command in your shell to add this server to Gemini CLI."})]}),d.jsxs("div",{className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Instructions"}),d.jsxs("ol",{className:"space-y-2 text-xs text-muted-foreground",children:[d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"1."}),d.jsx("span",{children:"Ensure the Gemini CLI executable is available in your path"})]}),B&&d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"2."}),d.jsx("span",{children:"Set these environment variables in your shell before running the command:"})]}),d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:B?"3.":"2."}),d.jsx("span",{children:"Execute the following snippet in your shell:"})]})]})]}),B&&d.jsxs("div",{children:[d.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Environment Variables"}),d.jsx("pre",{className:"bg-muted p-3 rounded-md text-xs overflow-x-auto",children:d.jsx("code",{children:B})})]}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"absolute top-2 right-2 z-10",children:d.jsx(Me,{variant:"ghost",size:"sm",className:"h-7 px-2 bg-background hover:bg-accent border border-border",onClick:()=>A(L),children:h?d.jsx(Or,{className:"size-3.5 text-green-600"}):d.jsx(wr,{className:"size-3.5"})})}),d.jsx("pre",{className:"bg-muted p-3 pr-14 rounded-md text-xs overflow-x-auto",children:d.jsx("code",{children:L})})]}),d.jsx("p",{className:"text-xs text-muted-foreground",children:"Restart Gemini CLI to load the new configuration."})]})]})}if(f==="codex-cli"){const{config:L,envVars:j}=FG(b,E,x);return d.jsxs(d.Fragment,{children:[d.jsxs(ls,{children:[d.jsx(cs,{children:"Add to Codex CLI"}),d.jsxs(Fp,{children:["Add this configuration to your"," ",d.jsx("code",{className:"text-foreground",children:"~/.codex/config.toml"})," ","file."]})]}),d.jsxs("div",{className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Instructions"}),d.jsxs("p",{className:"text-xs text-muted-foreground",children:["Add this configuration to your"," ",d.jsx("code",{className:"text-foreground",children:"~/.codex/config.toml"}),":"]})]}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"absolute top-2 right-2 z-10",children:d.jsx(Me,{variant:"ghost",size:"sm",className:"h-7 px-2 bg-background hover:bg-accent border border-border",onClick:()=>A(L),children:h?d.jsx(Or,{className:"size-3.5 text-green-600"}):d.jsx(wr,{className:"size-3.5"})})}),d.jsx("pre",{className:"bg-muted p-3 pr-14 rounded-md text-xs overflow-x-auto",children:d.jsx("code",{children:L})})]}),j.length>0&&d.jsx("div",{children:d.jsxs("p",{className:"text-xs text-muted-foreground",children:["(optional) If you would rather use variables from your system's environment, replace the"," ",d.jsx("code",{className:"text-foreground",children:"http_headers"})," key with the ",d.jsx("code",{className:"text-foreground",children:"env_http_headers"})," ","key as shown in the commented section above."]})}),d.jsx("p",{className:"text-xs text-muted-foreground",children:"Restart Codex CLI to load the new configuration."})]})]})}return null},O=d.jsxs(Me,{variant:"ghost",className:`bg-zinc-200 dark:bg-zinc-800 hover:bg-zinc-300 dark:hover:bg-zinc-700 rounded-full transition-colors px-3 flex items-center justify-center ${r}`,children:[d.jsxs("span",{className:"xl:hidden hidden sm:flex items-center gap-1",children:[d.jsx(mm,{className:"size-3"}),"Client"]}),d.jsxs("span",{className:"hidden xl:flex items-center gap-1",children:["Add to Client",d.jsx(hs,{className:"size-3"})]})]}),M=i?typeof i=="function"?i({isOpen:!1,onClick:()=>{}}):i:O;return d.jsxs(d.Fragment,{children:[d.jsxs(im,{children:[d.jsx(lm,{asChild:!0,children:M}),d.jsxs(jd,{align:"end",className:"w-auto min-w-[300px]",children:[t.map(L=>d.jsxs(Jr,{onClick:async()=>{await L.onClick()},className:"flex items-center gap-2",children:[L.icon,d.jsx("span",{className:"min-w-0 max-w-full whitespace-nowrap",children:L.label})]},L.id)),t.length>0&&d.jsx(Lu,{}),n.cursor&&d.jsxs(Jr,{onClick:w,className:"flex items-center gap-2",children:[d.jsx("img",{src:"https://cdn.simpleicons.org/cursor",alt:"Cursor",className:"h-4 w-4"}),d.jsx("span",{className:"min-w-0 max-w-full whitespace-nowrap",children:"Cursor"})]}),n.claudeCode&&d.jsxs(Jr,{onClick:T,className:"flex items-center gap-2",children:[d.jsx("img",{src:"https://cdn.simpleicons.org/claude",alt:"Claude",className:"h-4 w-4"}),d.jsx("span",{className:"min-w-0 max-w-full whitespace-nowrap",children:"Claude Code"})]}),n.claudeDesktop&&d.jsxs(Jr,{onClick:_,className:"flex items-center gap-2",children:[d.jsx("img",{src:"https://cdn.simpleicons.org/claude",alt:"Claude",className:"h-4 w-4"}),d.jsx("span",{className:"min-w-0 max-w-full whitespace-nowrap",children:"Claude Desktop"})]}),n.vsCode&&d.jsxs(Jr,{onClick:S,className:"flex items-center gap-2",children:[d.jsx(MG,{className:"h-4 w-4"}),d.jsx("span",{className:"min-w-0 max-w-full whitespace-nowrap",children:"VS Code"})]}),n.geminiCli&&d.jsxs(Jr,{onClick:k,className:"flex items-center gap-2",children:[d.jsx("img",{src:"https://cdn.simpleicons.org/googlegemini",alt:"Gemini",className:"h-4 w-4"}),d.jsx("span",{className:"min-w-0 max-w-full whitespace-nowrap",children:"Gemini CLI"})]}),n.codexCli&&d.jsxs(Jr,{onClick:R,className:"flex items-center gap-2",children:[d.jsx("img",{src:"https://inspector-cdn.mcp-use.com/providers/openai.png",alt:"Codex",className:"h-4 w-4"}),d.jsx("span",{className:"min-w-0 max-w-full whitespace-nowrap",children:"Codex CLI"})]})]})]}),d.jsx(tl,{open:l,onOpenChange:u,children:d.jsx(nl,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:C()})})]})}function ZF({className:e,state:t="collapsed",href:n="https://mcp-use.com"}){const[r,a]=y.useState(!1),o=.2,i=.7,l=.6,u=4,f=o+i+l,m=0,h=o/f,g=(o+i)/f,b=1;return d.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:Ue("flex items-center transition-opacity -my-3",t==="expanded"?"space-x-2":"",e),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[d.jsx("div",{className:"relative",children:d.jsxs(Fa.svg,{viewBox:"0 0 303 303",initial:"rest",animate:r?"hover":"rest",className:Ue("text-foreground",t==="expanded"?"size-[40px]":"size-[20px]"),children:[d.jsxs(Fa.g,{variants:{rest:{opacity:1},hover:{opacity:[1,0,0,1],transition:{duration:f,times:[m,h,g,b],ease:"easeInOut"}}},fill:"currentColor",fillRule:"nonzero",stroke:"currentColor",strokeWidth:u,strokeLinecap:"round",strokeLinejoin:"round",children:[d.jsx("path",{d:"m105.5 34.8.6.6c9.5 9.5 14.4 21.9 14.6 34.4a112.6 112.6 0 0 0 112.2 112.1h.6c12 .4 24 5.1 33.2 14.1l.6.6a50 50 0 0 1-70.1 71.3l-.6-.6A49.9 49.9 0 0 1 182 230 112.6 112.6 0 0 0 73.4 120.7h-.8a49.9 49.9 0 0 1-36.7-14l-.5-.6a50 50 0 0 1-.6-70.2l.6-.5a50 50 0 0 1 69.5-1.2l.6.6Z"}),d.jsx("circle",{cx:"70.3",cy:"232.3",r:"50"}),d.jsx("circle",{cx:"232.3",cy:"70.3",r:"50"})]}),d.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:u,strokeLinecap:"round",strokeLinejoin:"round",children:[d.jsx(yTe,{d:"m105.5 34.8.6.6c9.5 9.5 14.4 21.9 14.6 34.4a112.6 112.6 0 0 0 112.2 112.1h.6c12 .4 24 5.1 33.2 14.1l.6.6a50 50 0 0 1-70.1 71.3l-.6-.6A49.9 49.9 0 0 1 182 230 112.6 112.6 0 0 0 73.4 120.7h-.8a49.9 49.9 0 0 1-36.7-14l-.5-.6a50 50 0 0 1-.6-70.2l.6-.5a50 50 0 0 1 69.5-1.2l.6.6Z",times:{T0:m,T1:h,T2:g,T3:b},total:f}),d.jsx(qF,{cx:70.3,cy:232.3,r:50,times:{T0:m,T1:h,T2:g,T3:b},total:f}),d.jsx(qF,{cx:232.3,cy:70.3,r:50,times:{T0:m,T1:h,T2:g,T3:b},total:f})]})]})}),t==="expanded"&&d.jsxs("div",{className:"font-ubuntu flex-col items-start -space-y-1 mr-3 hidden xl:flex",children:[d.jsx("h1",{className:"text-xl font-medium",children:"mcp-use"}),d.jsx("span",{className:"text-lg text-muted-foreground tracking-wide font-sans font-light",children:"Inspector"})]})]})}function yTe({d:e,times:t,total:n}){const{T0:r,T1:a,T2:o,T3:i}=t;return d.jsx(Fa.path,{d:e,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:n,times:[r,a,o,i],ease:"easeInOut"}}}})}function qF({cx:e,cy:t,r:n,times:r,total:a}){const{T0:o,T1:i,T2:l,T3:u}=r;return d.jsx(Fa.circle,{cx:e,cy:t,r:n,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:a,times:[o,i,l,u],ease:"easeInOut"}}}})}function Kb({open:e,onOpenChange:t,serverUrl:n,serverName:r,serverId:a,headers:o,language:i}){const{prismStyle:l}=LI(),[u,f]=y.useState(!1),m=i==="typescript"?fxe(n,r,a,o):pxe(n,r,a,o),h=async()=>{await navigator.clipboard.writeText(m),f(!0),setTimeout(()=>f(!1),2e3)},g=i==="typescript"?"TypeScript":"Python",b=i==="typescript"?"npm install mcp-use":"pip install mcp-use";return d.jsx(tl,{open:e,onOpenChange:t,children:d.jsxs(nl,{className:"max-w-[90vw] max-h-[90vh] overflow-hidden flex flex-col",children:[d.jsxs(ls,{children:[d.jsxs(cs,{children:["Add to ",g," SDK"]}),d.jsxs(Fp,{children:["Copy the following code to integrate this server into your"," ",g," application using the mcp-use SDK."]})]}),d.jsxs("div",{className:"space-y-4 overflow-y-auto flex-1 min-h-0",children:[d.jsxs("div",{children:[d.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Instructions"}),d.jsxs("ol",{className:"space-y-2 text-xs text-muted-foreground",children:[d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"1."}),d.jsxs("span",{children:["Install the mcp-use package:"," ",d.jsx("code",{className:"text-foreground",children:b})]})]}),d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"2."}),d.jsxs("span",{children:["Copy the following code into your ",g," project:"]})]})]})]}),d.jsxs("div",{className:"relative w-full overflow-x-auto overflow-y-auto max-h-[60vh]",children:[d.jsx("div",{className:"absolute top-2 right-2 z-10",children:d.jsx(Me,{variant:"ghost",size:"sm",className:"h-7 px-2 bg-background hover:bg-accent border border-border",onClick:h,children:u?d.jsx(Or,{className:"size-3.5 text-green-600"}):d.jsx(wr,{className:"size-3.5"})})}),d.jsx(Em,{language:i,style:l,customStyle:{margin:0,padding:"1rem",paddingRight:"3rem",borderRadius:"0.5rem",fontSize:"0.75rem",background:"var(--muted)",width:"100%",maxWidth:"100%",overflow:"auto"},wrapLines:!0,wrapLongLines:!0,PreTag:"div",children:m})]})]})]})})}function GW({ref:e,shimmerColor:t,shimmerSize:n="0.05em",shimmerDuration:r="3s",borderRadius:a="100px",background:o,className:i,children:l,...u}){const{resolvedTheme:f}=Nw(),m=f==="dark"?"#000000":"#ffffff",h=f==="dark"?"rgba(255, 255, 255, 1)":"rgba(0, 0, 0, 1)",g=t||m,b=o||h;return d.jsxs("button",{style:{"--spread":"90deg","--shimmer-color":g,"--radius":a,"--speed":r,"--cut":n,"--bg":b},className:Ue("group relative z-0 flex cursor-pointer items-center justify-center overflow-hidden [border-radius:var(--radius)] border px-6 py-3 whitespace-nowrap [background:var(--bg)]","transform-gpu transition-transform duration-300 ease-in-out active:translate-y-px",f==="dark"?"border-black/10 text-black":"border-white/10 text-white",i),ref:e,...u,children:[d.jsx("div",{className:Ue("-z-30 blur-[2px]","[container-type:size] absolute inset-0 overflow-visible"),children:d.jsx("div",{className:"animate-shimmer-slide absolute inset-0 [aspect-ratio:1] h-[100cqh] [border-radius:0] [mask:none]",children:d.jsx("div",{className:"animate-spin-around absolute -inset-full w-auto [translate:0_0] rotate-0 [background:conic-gradient(from_calc(270deg-(var(--spread)*0.5)),transparent_0,var(--shimmer-color)_var(--spread),transparent_var(--spread))]"})})}),l,d.jsx("div",{className:Ue("absolute inset-0 size-full","rounded-2xl px-4 py-1.5 text-sm font-medium","transform-gpu transition-all duration-300 ease-in-out",f==="dark"?"shadow-[inset_0_-8px_10px_#0000001f] group-hover:shadow-[inset_0_-6px_10px_#0000003f] group-active:shadow-[inset_0_-10px_10px_#0000003f]":"shadow-[inset_0_-8px_10px_#ffffff1f] group-hover:shadow-[inset_0_-6px_10px_#ffffff3f] group-active:shadow-[inset_0_-10px_10px_#ffffff3f]")}),d.jsx("div",{className:Ue("absolute [inset:var(--cut)] -z-20 [border-radius:var(--radius)] [background:var(--bg)]")})]})}GW.displayName="ShimmerButton";function XF({status:e}){const t=o=>{switch(o){case"ready":return{color:"bg-emerald-500",ringColor:"ring-emerald-500",tooltip:"Connected"};case"failed":return{color:"bg-red-500",ringColor:"ring-red-500",tooltip:"Failed"};default:return{color:"bg-yellow-500",ringColor:"ring-yellow-500",tooltip:o}}},{color:n,ringColor:r,tooltip:a}=t(e);return d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:`absolute w-2 h-2 rounded-full ${r} animate-ping`}),d.jsx("div",{className:`relative w-2 h-2 rounded-full ${n}`})]})}),d.jsx(Yt,{children:d.jsx("p",{children:a})})]})}function JF({connections:e,selectedServer:t,onServerSelect:n,onOpenConnectionOptions:r,mobileMode:a=!1}){const o=bl(),[i,l]=y.useState(!1),[u,f]=y.useState(null),m=h=>{const g=e.find(b=>b.id===h);if(!g||g.state!=="ready"){At.error("Server is not connected and cannot be inspected");return}n(h)};return a?d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("div",{className:"relative",children:d.jsxs(im,{children:[d.jsx(lm,{asChild:!0,children:d.jsxs(Me,{variant:"ghost",className:"h-11 px-2 bg-black dark:bg-white text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200 flex items-center gap-1.5",children:[t?d.jsx(Hu,{server:t,size:"md"}):d.jsx(WH,{className:"h-5 w-5"}),d.jsx(hs,{className:"h-4 w-4"})]})}),d.jsxs(jd,{className:"w-[calc(100vw-2rem)] sm:w-[300px]",align:"start",children:[d.jsx(i_,{className:"cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:()=>o("/"),children:"MCP Servers"}),d.jsx(Lu,{}),e.length===0?d.jsx("div",{className:"px-2 py-4 text-sm text-muted-foreground dark:text-zinc-400 text-center",children:"No servers connected. Go to the dashboard to add one."}):e.map(h=>d.jsxs(Jr,{onClick:()=>m(h.id),className:"flex items-center gap-3",children:[d.jsx(Hu,{server:h,size:"sm"}),d.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[d.jsx("div",{className:"font-medium",children:h.name}),d.jsx(XF,{status:h.state})]}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(Me,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:g=>{g.stopPropagation(),f(h),l(!0)},children:d.jsx(Up,{className:"h-3 w-3"})}),d.jsx(Me,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:g=>{g.stopPropagation(),r(h.id)},children:d.jsx(Xu,{className:"h-3 w-3"})})]})]},h.id)),d.jsx(Lu,{}),d.jsx(Jr,{onClick:()=>o("/"),children:d.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:"+ Add new server"})})]})]})}),d.jsx(V_,{open:i,onOpenChange:l,connection:u})]}):d.jsx("div",{className:"flex items-center gap-2",children:d.jsxs("div",{className:"relative",children:[d.jsxs(im,{children:[d.jsx(lm,{asChild:!0,children:d.jsxs(GW,{className:Ue("min-w-0 sm:min-w-[200px] p-0 px-1 text-sm h-11 justify-start bg-black dark:bg-white text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200",!t&&"pl-4",t&&"pr-20"),children:[t&&d.jsx(Hu,{server:t,size:"md",className:"mr-2"}),d.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[d.jsx("span",{className:"truncate lg:max-w-[120px] xl:max-w-none",children:t?t.serverInfo?.title||t.serverInfo?.name||t.name:"Select server to inspect"}),t&&d.jsx("div",{className:"flex items-center gap-2",children:t.error&&t.state!=="ready"?d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx("button",{onClick:h=>{h.stopPropagation()},className:"w-2 h-2 rounded-full bg-rose-500 animate-status-pulse-red hover:bg-rose-600 transition-colors",title:"Click to copy error message","aria-label":"Copy error message to clipboard"})}),d.jsx(Yt,{children:d.jsx("p",{className:"max-w-xs",children:t.error})})]}):d.jsx("div",{className:`w-2 h-2 rounded-full ${t.state==="ready"?"bg-emerald-600 animate-status-pulse":t.state==="failed"?"bg-rose-600 animate-status-pulse-red":"bg-yellow-500 animate-status-pulse-yellow"}`})})]})]})}),t&&d.jsxs("div",{className:"absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1",children:[d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx("button",{type:"button",onClick:()=>{f(t),l(!0)},className:"p-1.5 hover:bg-white/10 dark:hover:bg-black/10 rounded-full transition-colors text-white dark:text-black","aria-label":"View server info",children:d.jsx(Up,{className:"h-4 w-4"})})}),d.jsx(Yt,{children:d.jsx("p",{children:"View server info"})})]}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx("button",{type:"button",onClick:()=>{r(t.id)},className:"p-1.5 hover:bg-white/10 dark:hover:bg-black/10 rounded-full transition-colors text-white dark:text-black","aria-label":"Edit connection settings",children:d.jsx(Xu,{className:"h-4 w-4"})})}),d.jsx(Yt,{children:d.jsx("p",{children:"Edit connection settings"})})]})]}),d.jsxs(jd,{className:"w-[calc(100vw-2rem)] sm:w-[300px]",align:"start",children:[d.jsx(i_,{className:"cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:()=>o("/"),children:"MCP Servers"}),d.jsx(Lu,{}),e.length===0?d.jsx("div",{className:"px-2 py-4 text-sm text-muted-foreground dark:text-zinc-400 text-center",children:"No servers connected. Go to the dashboard to add one."}):e.map(h=>d.jsxs(Jr,{onClick:()=>m(h.id),className:"flex items-center gap-3",children:[d.jsx(Hu,{server:h,size:"sm"}),d.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[d.jsx("div",{className:"font-medium",children:h.serverInfo?.title||h.serverInfo?.name||h.name}),d.jsx(XF,{status:h.state})]}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(Me,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:g=>{g.stopPropagation(),f(h),l(!0)},children:d.jsx(Up,{className:"h-3 w-3"})}),d.jsx(Me,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:g=>{g.stopPropagation(),r(h.id)},children:d.jsx(Xu,{className:"h-3 w-3"})})]})]},h.id)),d.jsx(Lu,{}),d.jsx(Jr,{onClick:()=>o("/"),children:d.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:"+ Add new server"})})]})]}),d.jsx(V_,{open:i,onOpenChange:l,connection:u})]})})}function QF({className:e}){const{theme:t,setTheme:n}=Nw(),r=y.useRef(null),a=()=>t==="system"?d.jsx(EU,{className:"size-4"}):t==="light"?d.jsx(TU,{className:"size-4"}):d.jsx(SU,{className:"size-4"}),o=async i=>{const l=r.current;if(!l){n(i);return}if(typeof document<"u"&&"startViewTransition"in document){await document.startViewTransition(()=>{ef.flushSync(()=>{n(i)})}).ready;const{top:u,left:f,width:m,height:h}=l.getBoundingClientRect(),g=u+h/2,b=f+m/2,E=window.innerWidth-f,x=window.innerHeight-u,w=Math.hypot(Math.max(f,E),Math.max(u,x));document.documentElement.animate({clipPath:[`circle(0px at ${b}px ${g}px)`,`circle(${w}px at ${b}px ${g}px)`]},{duration:700,easing:"ease-in-out",pseudoElement:"::view-transition-new(root)"})}else n(i)};return d.jsxs(im,{children:[d.jsx(lm,{asChild:!0,children:d.jsx(Me,{ref:r,variant:"ghost",size:"sm",className:Ue("p-2 hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full transition-colors",e),"aria-label":"Toggle theme",children:a()})}),d.jsx(jd,{align:"end",className:"min-w-0",children:d.jsxs(mce,{value:t,onValueChange:i=>o(i),children:[d.jsxs(ay,{value:"light",className:"pl-2 pr-0 flex items-center gap-2 justify-end",children:[d.jsx("span",{children:"Light"}),d.jsx(TU,{className:"mr-2 h-4 w-4"})]}),d.jsxs(ay,{value:"dark",className:"pl-2 pr-0 flex items-center gap-2 justify-end",children:[d.jsx("span",{children:"Dark"}),d.jsx(SU,{className:"mr-2 h-4 w-4"})]}),d.jsxs(ay,{value:"system",className:"pl-2 pr-0 flex items-center gap-2 justify-end",children:[d.jsx("span",{children:"System"}),d.jsx(EU,{className:"mr-2 h-4 w-4"})]})]})})]})}const e4=[{id:"tools",label:"Tools",icon:dc},{id:"prompts",label:"Prompts",icon:pm},{id:"resources",label:"Resources",icon:Mue},{id:"sampling",label:"Sampling",icon:BH},{id:"elicitation",label:"Elicitation",icon:KH},{id:"notifications",label:"Notifications",icon:KN},{id:"chat",label:"Chat",icon:Yue}];function t4(e,t){return e==="tools"?t.tools.length:e==="prompts"?t.prompts.length:e==="resources"?t.resources.length:e==="sampling"?t.pendingSamplingRequests?.length||0:e==="elicitation"?t.pendingElicitationRequests?.length||0:e==="notifications"?t.unreadNotificationCount:0}function n4(e,t,n){const r=["sampling","elicitation","notifications"];return n&&t>0&&r.includes(e)}function vTe({collapsed:e,onToggle:t}){return d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx("button",{onClick:t,className:Ue("shrink-0 p-1.5 rounded-md transition-all duration-500 ease-in-out cursor-pointer","text-muted-foreground hover:text-foreground","hover:bg-zinc-100 dark:hover:bg-zinc-800","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"),"aria-label":e?"Expand tabs":"Collapse tabs",type:"button",children:e?d.jsx(zH,{className:"h-4 w-4 transition-transform duration-500 ease-in-out"}):d.jsx(tw,{className:"h-4 w-4 transition-transform duration-500 ease-in-out"})})}),d.jsx(Yt,{children:d.jsx("p",{children:e?"Expand tabs":"Collapse tabs"})})]})}function wTe({connections:e,selectedServer:t,activeTab:n,onServerSelect:r,onTabChange:a,onCommandPaletteOpen:o,onOpenConnectionOptions:i,embedded:l=!1}){const{tunnelUrl:u}=kc(),f=t&&u,[m,h]=y.useState(!1),[g,b]=y.useState(!1),[E,x]=y.useState(!1),[w,S]=y.useState(!0),_=async()=>{if(u)try{await navigator.clipboard.writeText(`${u}/mcp`),h(!0),At.success("Tunnel URL copied to clipboard"),setTimeout(()=>h(!1),2e3)}catch{At.error("Failed to copy URL")}};return d.jsxs("header",{className:"w-full mx-auto",children:[d.jsxs("div",{className:"flex lg:hidden flex-col gap-3",children:[d.jsxs("div",{className:"flex items-center justify-between w-full",children:[!l&&d.jsx("div",{className:"flex-1 flex justify-start",children:d.jsx(JF,{connections:e,selectedServer:t,onServerSelect:r,onOpenConnectionOptions:i,mobileMode:!0})}),!l&&d.jsx("div",{className:"flex-shrink-0 flex justify-center",children:d.jsx("div",{className:"scale-150",children:d.jsx(ZF,{state:"collapsed"})})}),!l&&d.jsxs("div",{className:"flex-1 flex justify-end items-center gap-2",children:[t&&(()=>{const T=t.serverInfo?.title||t.serverInfo?.name||t.name;return d.jsxs(d.Fragment,{children:[d.jsx(YF,{serverConfig:{url:u?`${u}/mcp`:t.url,name:T,headers:t.customHeaders,serverId:t.id},onSuccess:k=>At.success(`Opening in ${k}...`),onError:k=>At.error(`Failed: ${k.message}`),additionalItems:[{id:"ts-sdk",label:"TypeScript SDK",icon:d.jsx("img",{src:"https://cdn.simpleicons.org/typescript",alt:"TypeScript",className:"h-4 w-4"}),onClick:()=>b(!0)},{id:"py-sdk",label:"Python SDK",icon:d.jsx("img",{src:"https://cdn.simpleicons.org/python",alt:"Python",className:"h-4 w-4"}),onClick:()=>x(!0)}],trigger:d.jsxs(Me,{variant:"ghost",className:"bg-zinc-200 dark:bg-zinc-800 hover:bg-zinc-300 dark:hover:bg-zinc-700 rounded-full transition-colors px-3 flex items-center justify-center p-2","aria-label":"Add to Client",children:[d.jsxs("span",{className:"xl:hidden hidden sm:flex items-center gap-1",children:[d.jsx(mm,{className:"size-3"}),"Client"]}),d.jsxs("span",{className:"hidden xl:flex items-center gap-1",children:["Add to Client",d.jsx(hs,{className:"size-3"})]})]})}),d.jsx(Kb,{open:g,onOpenChange:b,serverUrl:u?`${u}/mcp`:t.url,serverName:T,serverId:void 0,headers:t.customHeaders,language:"typescript"}),d.jsx(Kb,{open:E,onOpenChange:x,serverUrl:u?`${u}/mcp`:t.url,serverName:T,serverId:void 0,headers:t.customHeaders,language:"python"})]})})(),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",asChild:!0,children:d.jsx("a",{href:"https://github.com/mcp-use/mcp-use",target:"_blank",rel:"noopener noreferrer",className:"p-2","aria-label":"GitHub",children:d.jsx(KF,{className:"h-4 w-4"})})})}),d.jsx(Yt,{children:d.jsx("p",{children:"Give us a star ⭐"})})]}),d.jsx(QF,{})]})]}),t&&d.jsx("div",{className:"w-full",children:d.jsx($T,{value:n,onValueChange:T=>a(T),collapsed:w,onCollapsedChange:S,children:d.jsx(UT,{className:"w-full justify-center",children:e4.map(T=>{const k=t4(T.id,t),R=n4(T.id,k,w);return d.jsxs(zT,{value:T.id,icon:T.icon,showDot:R,className:Ue("[&>svg]:mr-0 flex-1 flex-row gap-2 relative",w&&"pl-2"),children:[k>0&&!w&&d.jsx("span",{className:Ue(n===T.id?"dark:bg-black":"dark:bg-zinc-700","bg-zinc-200 text-zinc-700 dark:text-zinc-300 text-[10px] px-1.5 py-0.5 rounded-full font-medium"),children:k}),d.jsx("span",{className:"sr-only",children:T.label})]},T.id)})})})})]}),d.jsxs("div",{className:"hidden lg:flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"flex items-center flex-wrap gap-2 md:space-x-6 space-x-2",children:[!l&&d.jsx(JF,{connections:e,selectedServer:t,onServerSelect:r,onOpenConnectionOptions:i}),t&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx($T,{value:n,onValueChange:T=>a(T),collapsed:w,onCollapsedChange:S,children:d.jsx(UT,{className:"overflow-x-auto",collapsible:!0,children:e4.map(T=>{const k=t4(T.id,t),R=k>0?`${T.label} (${k})`:T.label,A=n4(T.id,k,w);return d.jsx(zT,{value:T.id,icon:T.icon,showDot:A,className:Ue("[&>svg]:mr-0 lg:[&>svg]:mr-2 relative",w&&"pl-4"),title:R,children:d.jsxs("div",{className:"items-center gap-2 hidden lg:flex",children:[T.label,k>0&&d.jsx("span",{className:Ue(n===T.id?" dark:bg-black ":"dark:bg-zinc-700","bg-zinc-200 text-zinc-700 dark:text-zinc-300 text-xs px-2 py-0.5 rounded-full font-medium"),children:k})]})})})})}),d.jsx(vTe,{collapsed:w,onToggle:()=>S(!w)})]}),f&&d.jsxs(o7,{children:[d.jsx(s7,{asChild:!0,children:d.jsxs("button",{className:"flex items-center gap-2 px-3 py-1.5 bg-gradient-to-r from-purple-500/10 to-pink-500/10 dark:from-purple-500/20 dark:to-pink-500/20 border border-purple-500/30 dark:border-purple-500/40 rounded-full hover:from-purple-500/20 hover:to-pink-500/20 dark:hover:from-purple-500/30 dark:hover:to-pink-500/30 transition-colors cursor-pointer",children:[d.jsx(hm,{className:"size-4 text-purple-600 dark:text-purple-400 animate-pulse"}),d.jsx("span",{className:"text-xs font-medium text-purple-700 dark:text-purple-300 hidden lg:inline",children:"Tunnel"})]})}),d.jsx(gO,{className:"w-[calc(100vw-2rem)] sm:w-96",align:"start",children:d.jsxs("div",{className:"space-y-4",children:[d.jsxs("div",{children:[d.jsxs("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:[d.jsx(hm,{className:"size-4 text-purple-600 dark:text-purple-400"}),"Tunnel URL"]}),d.jsxs("div",{className:"flex items-center gap-2 p-2 py-0 bg-muted rounded-full",children:[d.jsxs("code",{className:"flex-1 text-[10px] font-mono",children:[u,"/mcp"]}),d.jsx(Me,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:_,children:m?d.jsx(Or,{className:"size-3.5 text-green-600"}):d.jsx(wr,{className:"size-3.5"})})]})]}),d.jsxs("div",{children:[d.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Use in ChatGPT"}),d.jsxs("ol",{className:"space-y-2 text-xs text-muted-foreground",children:[d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"1."}),d.jsxs("span",{children:["Enable"," ",d.jsx("span",{className:"font-medium text-foreground",children:"dev mode"})," ","from settings"]})]}),d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"2."}),d.jsxs("span",{children:["In"," ",d.jsx("span",{className:"font-medium text-foreground",children:"App & Connectors"})," ","click on"," ",d.jsx("span",{className:"font-medium text-foreground",children:"create"})]})]}),d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"3."}),d.jsx("span",{children:"Use the tunnel URL in the input"})]})]})]})]})})]})]}),!l&&d.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-shrink-0",children:[t&&(()=>{const T=t.serverInfo?.title||t.serverInfo?.name||t.name;return d.jsxs(d.Fragment,{children:[d.jsx(YF,{serverConfig:{url:u?`${u}/mcp`:t.url,name:T,headers:t.customHeaders,serverId:t.id},onSuccess:k=>At.success(`Opening in ${k}...`),onError:k=>At.error(`Failed: ${k.message}`),additionalItems:[{id:"ts-sdk",label:"TypeScript SDK",icon:d.jsx("img",{src:"https://cdn.simpleicons.org/typescript",alt:"TypeScript",className:"h-4 w-4"}),onClick:()=>b(!0)},{id:"py-sdk",label:"Python SDK",icon:d.jsx("img",{src:"https://cdn.simpleicons.org/python",alt:"Python",className:"h-4 w-4"}),onClick:()=>x(!0)}],trigger:d.jsxs(Me,{variant:"ghost",className:"bg-zinc-200 dark:bg-zinc-800 hover:bg-zinc-300 dark:hover:bg-zinc-700 rounded-full transition-colors px-3 flex items-center justify-center","aria-label":"Add to Client",children:[d.jsxs("span",{className:"xl:hidden hidden sm:flex items-center gap-1",children:[d.jsx(mm,{className:"size-3"}),"Client"]}),d.jsxs("span",{className:"hidden xl:flex items-center gap-1",children:["Add to Client",d.jsx(hs,{className:"size-3"})]})]})}),d.jsx(Kb,{open:g,onOpenChange:b,serverUrl:u?`${u}/mcp`:t.url,serverName:T,serverId:void 0,headers:t.customHeaders,language:"typescript"}),d.jsx(Kb,{open:E,onOpenChange:x,serverUrl:u?`${u}/mcp`:t.url,serverName:T,serverId:void 0,headers:t.customHeaders,language:"python"})]})})(),d.jsx(QF,{}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsxs(Me,{variant:"ghost",className:"hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full px-1 -mx-3 flex gap-1",onClick:o,children:[d.jsx(yue,{className:"size-4"}),d.jsx("span",{className:"text-base font-mono hidden sm:inline",children:"K"})]})}),d.jsx(Yt,{children:d.jsx("p",{children:"Command Palette"})})]}),d.jsxs(Wt,{children:[d.jsx(Kt,{asChild:!0,children:d.jsx(Me,{variant:"ghost",size:"sm",asChild:!0,children:d.jsxs("a",{href:"https://github.com/mcp-use/mcp-use",className:"flex items-center gap-2",target:"_blank",rel:"noopener noreferrer",children:[d.jsx(KF,{className:"h-4 w-4"}),d.jsx("span",{className:"hidden xl:inline",children:"Github"})]})})}),d.jsx(Yt,{children:d.jsx("p",{children:"Give us a star ⭐"})})]}),d.jsx(ZF,{state:"expanded"})]})]})]})}function xTe({children:e}){const t=bl(),n=Aa(),{servers:r,addServer:a,removeServer:o,updateServer:i,storageLoaded:l}=Wm(),u=y.useCallback((D,$,G,W)=>{a(D,{url:D,name:$,proxyConfig:G,transportType:W,preventAutoAuth:!0})},[a]),f=y.useCallback(async(D,$)=>{try{await i(D,$)}catch(G){console.error(`[Layout] Failed to update connection ${D}:`,G)}},[i]),{selectedServerId:m,setSelectedServerId:h,activeTab:g,setActiveTab:b,navigateToItem:E,setTunnelUrl:x,tunnelUrl:w,isEmbedded:S,embeddedConfig:_,setEmbeddedMode:T}=kc(),[k,R]=y.useState(!1),[A,C]=y.useState(null),O=U0e();y.useEffect(()=>{const D=new URLSearchParams(n.search),$=D.get("embedded")==="true",G=D.get("embeddedConfig");if($){let W={};if(G)try{W=JSON.parse(G)}catch(re){console.error("Failed to parse embeddedConfig:",re)}T(!0,W)}},[]),y.useEffect(()=>{const $=new URLSearchParams(n.search).get("tunnelUrl");x($)},[n.search,x]),y.useEffect(()=>{const $=new URLSearchParams(n.search).get("tab");$&&["tools","prompts","resources","chat","sampling","elicitation","notifications"].includes($)&&b($)},[n.search,b]),y.useEffect(()=>{const D=W=>{const pe=W.detail.requestId;m&&E(m,"sampling",pe)},$=W=>{const pe=W.detail.requestId;m&&E(m,"elicitation",pe)},G=W=>{const pe=W.detail.toolName;m&&pe?E(m,"tools",pe):m&&b("tools")};return window.addEventListener("navigate-to-sampling",D),window.addEventListener("navigate-to-elicitation",$),window.addEventListener("navigate-to-tool-result",G),()=>{window.removeEventListener("navigate-to-sampling",D),window.removeEventListener("navigate-to-elicitation",$),window.removeEventListener("navigate-to-tool-result",G)}},[m,b,E]);const M=y.useRef(null),L=y.useRef(null),j=y.useRef(null),{isAutoConnecting:B}=$0e({connections:r,addConnection:u,removeConnection:o,configLoaded:l,embedded:S}),K=y.useCallback(D=>{ra.getInstance().capture(new zce({trigger:D})).catch(()=>{}),R(!0)},[]),Z=D=>{const $=r.find(me=>me.id===D);if(!$||$.state!=="ready"){At.error("Server is not connected and cannot be inspected");return}h(D);const G=new URLSearchParams(n.search),W=G.get("tunnelUrl"),re=G.get("tab"),pe=new URLSearchParams;pe.set("server",D),W&&pe.set("tunnelUrl",W),re&&pe.set("tab",re),t(`/?${pe.toString()}`)},te=y.useCallback(D=>{C(D)},[]),V=y.useCallback(D=>{A&&(D.url!==A?(o(A),u(D.url,D.name,D.proxyConfig,D.transportType)):f(A,{name:D.name,proxyConfig:D.proxyConfig,transportType:D.transportType}),C(null),At.success("Connection settings updated"))},[A,o,u,f]),Y=(D,$,G)=>{if(console.warn("[Layout] handleCommandPaletteNavigate called:",{tab:D,itemName:$,serverId:G}),G){const W=r.find(X=>X.id===G);if(console.warn("[Layout] Server lookup:",{serverId:G,serverFound:!!W,serverState:W?.state}),!W||W.state!=="ready"){console.warn("[Layout] Server not ready, showing error"),At.error("Server is not connected and cannot be inspected");return}console.warn("[Layout] Calling navigateToItem:",{serverId:G,tab:D,itemName:$}),E(G,D,$);const re=new URLSearchParams(n.search),pe=re.get("tunnelUrl"),me=re.get("tab"),ne=new URLSearchParams;ne.set("server",G),pe&&ne.set("tunnelUrl",pe),D?ne.set("tab",D):me&&ne.set("tab",me);const J=`/?${ne.toString()}`;console.warn("[Layout] Navigating to:",J),t(J)}else console.warn("[Layout] No serverId, just updating tab to:",D),b(D)},F=r.find(D=>D.id===m),ae=F?F.tools.map(D=>({...D,_serverId:F.id})):r.flatMap(D=>D.state==="ready"?D.tools.map($=>({...$,_serverId:D.id,_serverName:D.name})):[]),ee=F?F.prompts.map(D=>({...D,_serverId:F.id})):r.flatMap(D=>D.state==="ready"?D.prompts.map($=>({...$,_serverId:D.id,_serverName:D.name})):[]),P=F?F.resources.map(D=>({...D,_serverId:F.id})):r.flatMap(D=>D.state==="ready"?D.resources.map($=>({...$,_serverId:D.id,_serverName:D.name})):[]);if(y.useEffect(()=>{const $=new URLSearchParams(n.search).get("server"),G=$?decodeURIComponent($):null;G!==m&&h(G)},[n.search,m,h]),y.useEffect(()=>{const $=new URLSearchParams(n.search).get("server");if(!$)return;const G=decodeURIComponent($),W=r.find(re=>re.id===G);if(!W){const re=setTimeout(()=>t("/"),3e3);return()=>clearTimeout(re)}if(W.state==="failed"){const re=setTimeout(()=>t("/"),2e3);return()=>clearTimeout(re)}},[n.search,t,r]),NG({onCommandPalette:()=>K("keyboard"),onToolsTab:()=>{F&&b("tools")},onPromptsTab:()=>{F&&b("prompts")},onResourcesTab:()=>{F&&b("resources")},onChatTab:()=>{F&&b("chat")},onHome:()=>{t("/")},onFocusSearch:()=>{g==="tools"&&M.current?M.current.focusSearch():g==="prompts"&&L.current?L.current.focusSearch():g==="resources"&&j.current&&j.current.focusSearch()},onBlurSearch:()=>{g==="tools"&&M.current?M.current.blurSearch():g==="prompts"&&L.current?L.current.blurSearch():g==="resources"&&j.current&&j.current.blurSearch()}}),B)return d.jsx("div",{className:"h-screen bg-white dark:bg-zinc-900 flex items-center justify-center",children:d.jsxs("div",{className:"flex flex-col items-center gap-4",children:[d.jsx(gs,{className:"h-8 w-8 text-zinc-600 dark:text-zinc-400"}),d.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Connecting to MCP server..."})]})});const H=S?{backgroundColor:_.backgroundColor||"#f3f3f3",padding:_.padding||"0.5rem"}:{},U=S?"h-screen flex flex-col gap-2 sm:gap-4":"h-screen bg-[#f3f3f3] dark:bg-black flex flex-col px-2 py-2 sm:px-4 sm:py-4 gap-2 sm:gap-4";return d.jsx(WN,{children:d.jsxs("div",{className:U,style:H,children:[d.jsx(wTe,{connections:r,selectedServer:F,activeTab:g,onServerSelect:Z,onTabChange:b,onCommandPaletteOpen:()=>K("button"),onOpenConnectionOptions:te,embedded:S}),d.jsx("main",{className:"flex-1 w-full mx-auto bg-white dark:bg-black rounded-2xl border border-zinc-200 dark:border-zinc-700 p-0 overflow-auto",children:d.jsx(hTe,{selectedServer:F,activeTab:g,toolsSearchRef:M,promptsSearchRef:L,resourcesSearchRef:j,children:e})}),d.jsx(hxe,{isOpen:k,onOpenChange:R,tools:ae,prompts:ee,resources:P,savedRequests:O,connections:r,selectedServer:F,tunnelUrl:w,onNavigate:Y,onServerSelect:Z}),d.jsx(V8,{connection:A&&r.find(D=>D.id===A)||null,open:A!==null,onOpenChange:D=>{D||C(null)},onConnect:V})]})})}function ETe(){const[e,t]=y.useState("processing"),[n,r]=y.useState("");return y.useEffect(()=>{console.log("[OAuthCallback] Component mounted, handling authorization..."),console.log("[OAuthCallback] Current URL:",window.location.href),xN().then(()=>{console.log("[OAuthCallback] Authorization successful"),t("success")}).catch(a=>{console.error("[OAuthCallback] Authorization failed:",a),t("error"),r(a instanceof Error?a.message:String(a))})},[]),e==="processing"?d.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:d.jsxs("div",{className:"flex flex-col items-center gap-4",children:[d.jsx(cl,{className:"h-8 w-8 animate-spin text-zinc-600 dark:text-zinc-400"}),d.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Completing authentication..."})]})}):e==="error"?d.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:d.jsxs("div",{className:"max-w-md p-6",children:[d.jsx("h1",{className:"text-xl font-semibold text-red-600 dark:text-red-400 mb-2",children:"Authentication Error"}),d.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400 mb-4",children:n}),d.jsx("p",{className:"text-xs text-zinc-500 dark:text-zinc-500",children:"You can close this window and try again."})]})}):d.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:d.jsxs("div",{className:"max-w-md p-6",children:[d.jsx("h1",{className:"text-xl font-semibold text-green-600 dark:text-green-400 mb-2",children:"Authentication Successful!"}),d.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Redirecting you back..."})]})})}var STe=(e,t,n,r,a,o,i,l)=>{let u=document.documentElement,f=["light","dark"];function m(b){(Array.isArray(e)?e:[e]).forEach(E=>{let x=E==="class",w=x&&o?a.map(S=>o[S]||S):a;x?(u.classList.remove(...w),u.classList.add(o&&o[b]?o[b]:b)):u.setAttribute(E,b)}),h(b)}function h(b){l&&f.includes(b)&&(u.style.colorScheme=b)}function g(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)m(r);else try{let b=localStorage.getItem(t)||n,E=i&&b==="system"?g():b;m(E)}catch{}},_Te=y.createContext(void 0),TTe={setTheme:e=>{},themes:[]},NTe=()=>{var e;return(e=y.useContext(_Te))!=null?e:TTe};y.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:a,defaultTheme:o,value:i,themes:l,nonce:u,scriptProps:f})=>{let m=JSON.stringify([n,t,o,e,l,i,r,a]).slice(1,-1);return y.createElement("script",{...f,suppressHydrationWarning:!0,nonce:typeof window>"u"?u:"",dangerouslySetInnerHTML:{__html:`(${STe.toString()})(${m})`}})});function CTe({...e}){const{theme:t="system"}=NTe();return d.jsx(Ume,{theme:t,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...e})}function RTe(){const t=new URLSearchParams(window.location.search).get("embedded")==="true",n=y.useMemo(()=>t?void 0:new eae("mcp-inspector-connections"),[t]);return d.jsx(Xge,{children:d.jsx(RB,{storageProvider:n,enableRpcLogging:!0,defaultAutoProxyFallback:{enabled:!0,proxyAddress:`${window.location.origin}/inspector/api/proxy`},onServerAdded:(r,a)=>{console.log("[Inspector] Server added:",r,a.state)},onServerRemoved:r=>{console.log("[Inspector] Server removed:",r)},onServerStateChange:(r,a)=>{console.log("[Inspector] Server state changed:",r,a)},onSamplingRequest:(r,a,o,i,l)=>{const u=At(d.jsx(cTe,{requestId:r.id,serverName:o,onViewDetails:()=>{const f=new CustomEvent("navigate-to-sampling",{detail:{requestId:r.id}});window.dispatchEvent(f),At.dismiss(u)},onApprove:f=>{i(r.id,f),At.success("Sampling request approved"),At.dismiss(u)},onDeny:()=>{l(r.id,"User denied from toast"),At.dismiss(u)}}),{duration:1/0})},onElicitationRequest:(r,a,o,i,l)=>{const u=r.request.mode||"form",f=r.request.message,m=u==="url"&&"url"in r.request?r.request.url:void 0,h=At(d.jsx(cae,{requestId:r.id,serverName:o,mode:u,message:f,url:m,onViewDetails:()=>{const g=new CustomEvent("navigate-to-elicitation",{detail:{requestId:r.id}});window.dispatchEvent(g),At.dismiss(h)},onOpenUrl:u==="url"&&m?()=>{window.open(m,"_blank"),At.dismiss(h)}:void 0,onCancel:()=>{l(r.id,"User cancelled from toast"),At.dismiss(h)}}),{duration:1/0})},children:d.jsxs(P0e,{children:[d.jsx(Qpe,{basename:"/inspector",children:d.jsxs(Gfe,{children:[d.jsx(w_,{path:"/oauth/callback",element:d.jsx(ETe,{})}),d.jsx(w_,{path:"/",element:d.jsx(xTe,{children:d.jsx(j0e,{})})})]})}),d.jsx(CTe,{position:"top-center"})]})})})}const r4=new URLSearchParams(window.location.search);if(r4.has("code")||r4.has("error"))try{xN()}catch(e){console.error("[inspector] OAuth callback error:",e)}const a4=document.getElementById("root");a4?lae.createRoot(a4).render(d.jsx(RTe,{})):console.error("[inspector] Root element not found");const kTe=Object.freeze(Object.defineProperty({__proto__:null,clearRpcLogs:Uy,getAllRpcLogs:SN,getRpcLogs:kB,subscribeToRpcLogs:_N,wrapTransportForLogging:AB},Symbol.toStringTag,{value:"Module"}));export{oy as $,Ec as A,_pe as B,N_ as C,BTe as D,ws as E,uw as F,HTe as G,JN as H,Na as I,zpe as J,b_ as K,ac as L,hfe as M,ua as N,rNe as O,ofe as P,mpe as Q,wNe as R,ANe as S,pNe as T,aNe as U,Qpe as V,y6 as W,SNe as X,ql as Y,QN as Z,ze as _,Ua as a,_fe as a$,b6 as a0,yNe as a1,tNe as a2,vNe as a3,tme as a4,nNe as a5,Cde as a6,p6 as a7,w_ as a8,Nc as a9,bNe as aA,ime as aB,xNe as aC,zTe as aD,ENe as aE,ga as aF,Yy as aG,oNe as aH,x_ as aI,INe as aJ,qde as aK,FTe as aL,gm as aM,Ro as aN,sNe as aO,Gde as aP,eme as aQ,RNe as aR,JTe as aS,dC as aT,XTe as aU,Mfe as aV,CNe as aW,Pfe as aX,TNe as aY,NNe as aZ,sme as a_,Gfe as aa,Ype as ab,nme as ac,kNe as ad,GTe as ae,si as af,gl as ag,iw as ah,lf as ai,ka as aj,oo as ak,sw as al,iNe as am,dNe as an,cNe as ao,qH as ap,yC as aq,hNe as ar,XH as as,ZH as at,eC as au,gNe as av,mNe as aw,pC as ax,Et as ay,rh as az,ONe as b,nr as b$,Tc as b0,rme as b1,uC as b2,Aa as b3,KTe as b4,cC as b5,bl as b6,Lfe as b7,WTe as b8,Nfe as b9,dr as bA,de as bB,wt as bC,An as bD,b3 as bE,$Te as bF,no as bG,rr as bH,PTe as bI,MTe as bJ,fr as bK,Ep as bL,jTe as bM,pl as bN,dJ as bO,dX as bP,EX as bQ,IZ as bR,LZ as bS,uJ as bT,uX as bU,DTe as bV,NZ as bW,ol as bX,OQ as bY,ree as bZ,m3 as b_,YTe as ba,oC as bb,nh as bc,ZTe as bd,qTe as be,Cfe as bf,_Ne as bg,w6 as bh,cme as bi,Pte as bj,ITe as bk,Um as bl,qb as bm,Ure as bn,Sv as bo,rs as bp,Fe as bq,$re as br,Bre as bs,v$ as bt,OTe as bu,zre as bv,at as bw,nt as bx,er as by,eee as bz,Dpe as c,IX as c0,y4 as c1,vZ as c2,ey as c3,sZ as c4,Hre as c5,iZ as c6,xN as c7,wZ as c8,hpe as d,le as e,Mu as f,fc as g,QTe as h,eNe as i,OV as j,ppe as k,Efe as l,Uo as m,Sfe as n,ym as o,LTe as p,So as q,y as r,jpe as s,afe as t,fC as u,VTe as v,v_ as w,fNe as x,uNe as y,lNe as z};