import{r as U,c as B,v as S,j as d}from"./index-DAmbTOxS.js";import{u as z}from"./use-mcp-resources-D8ui0z-w.js";import{W as F,T as W}from"./types-tRNNwmgc.js";const N=["default-src 'none'","script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval'","style-src 'unsafe-inline'","img-src * data: blob:","font-src data:","connect-src 'none'","frame-src 'none'","worker-src blob:","form-action 'none'","base-uri 'none'"].join("; ");function Z(s,e={}){const n=`<meta http-equiv="Content-Security-Policy" content="${Y(e)}">`,o=/<head(\s[^>]*)?>|<HEAD(\s[^>]*)?>/i,c=s.match(o);if(c){const r=(c.index??0)+c[0].length;return s.slice(0,r)+`
`+n+s.slice(r)}const a=/<html(\s[^>]*)?>|<HTML(\s[^>]*)?>/i,i=s.match(a);if(i){const r=(i.index??0)+i[0].length;return s.slice(0,r)+`
<head>
`+n+`
</head>`+s.slice(r)}const u=/<!DOCTYPE[^>]*>/i,l=s.match(u);if(l){const r=(l.index??0)+l[0].length;return s.slice(0,r)+`
<head>
`+n+`
</head>`+s.slice(r)}return`<head>
`+n+`
</head>
`+s}const q=/^https?:\/\/[a-zA-Z0-9._-]+(:\d+)?$/;function L(s){return!s||s.length===0?[]:s.filter(e=>q.test(e))}function Y(s){if(s.csp)return s.csp;const e=s.resourceCsp;if(!e)return N;const t=L(e.resourceDomains),n=L(e.connectDomains),o=L(e.frameDomains),c=L(e.baseUriDomains),a=t.length>0,i=n.length>0,u=o.length>0,l=c.length>0;if(!a&&!i&&!u&&!l)return N;const r=t.join(" ");return["default-src 'none'",a?`script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' ${r}`:"script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval'",a?`style-src 'unsafe-inline' ${r}`:"style-src 'unsafe-inline'",a?`img-src * data: blob: ${r}`:"img-src * data: blob:",a?`font-src data: ${r}`:"font-src data:",i?`connect-src ${n.join(" ")}`:"connect-src 'none'",u?`frame-src ${o.join(" ")}`:"frame-src 'none'","worker-src blob:","form-action 'none'",l?`base-uri ${c.join(" ")}`:"base-uri 'none'"].join("; ")}const G={name:"MCP Mesh",version:"1.0.0"},J={openLinks:{},serverTools:{},serverResources:{},logging:{},message:{},downloadFile:{}},K=15e3;function Q(){return typeof window>"u"?"light":window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"}function V(){return typeof navigator>"u"?"en":navigator.language??"en"}function X(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}function ee(){return typeof navigator>"u"?"web":/Mobi|Android/i.test(navigator.userAgent)?"mobile":"web"}function te(s,e,t){return{theme:Q(),displayMode:s,availableDisplayModes:["inline","fullscreen"],locale:V(),timeZone:X(),platform:ee(),...e!=null&&{toolInfo:e},...t!=null&&{containerDimensions:{maxHeight:t}}}}class ne{bridge=null;timeout=null;disposed=!1;snapshot;listeners=new Set;config;constructor(e){this.config=e,this.snapshot=Object.freeze({height:e.minHeight,isLoading:!0,error:null})}subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));getSnapshot=()=>this.snapshot;updateConfig(e){const t=this.config;this.config=e,!(!this.bridge||this.disposed)&&(e.toolInput!==t.toolInput&&e.toolInput!=null&&this.bridge.sendToolInput({arguments:e.toolInput}),e.toolResult!==t.toolResult&&e.toolResult!=null&&this.bridge.sendToolResult(e.toolResult))}set(e){const t=this.snapshot,n={...t,...e};if(!(n.height===t.height&&n.isLoading===t.isLoading&&n.error===t.error)){this.snapshot=Object.freeze(n);for(const o of this.listeners)o()}}teardown(){this.disposed=!0,this.bridge&&(this.bridge.teardownResource({}).catch(()=>{}),this.bridge.close(),this.bridge=null),this.timeout&&(clearTimeout(this.timeout),this.timeout=null)}attach=e=>{if(this.teardown(),this.disposed=!1,this.set({height:this.config.minHeight,isLoading:!0,error:null}),!!e){e.onerror=()=>{this.disposed||this.set({error:"Failed to load app",isLoading:!1})};try{const{client:t,displayMode:n,maxHeight:o,toolInfo:c}=this.config,a=te(n,c,o),i=new F(t,G,J,{hostContext:a});this.bridge=i,this.registerHandlers(i),this.startInitTimeout(),this.registerInitHandler(i),this.connectTransport(i,e)}catch(t){this.clearTimeout(),console.error("Failed to create AppBridge:",t),this.set({error:t instanceof Error?t.message:"Unknown error",isLoading:!1})}}};registerHandlers(e){e.onopenlink=async({url:t})=>{let n=null;try{n=new URL(t)}catch{}if(!n||!["http:","https:"].includes(n.protocol))throw new Error("Only http and https URLs are allowed");return window.open(t,"_blank","noopener,noreferrer"),{}},e.onmessage=async t=>(this.config.onMessage?.(t),{}),e.onsizechange=({height:t})=>{if(!this.disposed&&t!=null){const{minHeight:n,maxHeight:o}=this.config;this.set({height:Math.max(n,Math.min(o,t))})}},e.onloggingmessage=({level:t,data:n})=>{console[t==="error"?"error":"debug"](`[MCP App ${this.config.toolInfo?.tool.name??"unknown"}]`,n)},e.ondownloadfile=async({contents:t})=>{for(const n of t)if(n.type==="resource"){const o=n.resource,c="blob"in o?new Blob([Uint8Array.from(atob(o.blob),u=>u.charCodeAt(0))],{type:o.mimeType}):new Blob([o.text??""],{type:o.mimeType}),a=URL.createObjectURL(c),i=document.createElement("a");i.href=a,i.download=o.uri.split("/").pop()??"download",i.click(),URL.revokeObjectURL(a)}else n.type==="resource_link"&&window.open(n.uri,"_blank");return{}}}registerInitHandler(e){e.oninitialized=()=>{if(this.disposed)return;this.clearTimeout(),this.set({isLoading:!1});const{toolInput:t,toolResult:n}=this.config;t!=null&&e.sendToolInput({arguments:t}),n!=null&&e.sendToolResult(n)}}startInitTimeout(){this.timeout=setTimeout(()=>{this.disposed||this.set({error:"App took too long to load",isLoading:!1})},K)}clearTimeout(){this.timeout&&(globalThis.clearTimeout(this.timeout),this.timeout=null)}connectTransport(e,t){if(!t.contentWindow){console.warn("iframe contentWindow not yet available");return}const n=new W(t.contentWindow,t.contentWindow);e.connect(n).catch(o=>{this.disposed||(this.clearTimeout(),console.error("AppBridge connect failed:",o),this.set({error:o instanceof Error?o.message:"Connection failed",isLoading:!1}))})}}function se(s){const e=U.useRef(new ne(s));U.useEffect(()=>{e.current.updateConfig(s)},[s]);const{height:t,isLoading:n,error:o}=U.useSyncExternalStore(e.current.subscribe,e.current.getSnapshot);return{height:t,isLoading:n,error:o,iframeRef:e.current.attach}}function oe(s){const e=s?.contents?.[0];return!e||!("text"in e)||!e.text?null:Z(e.text,{resourceCsp:e._meta?.ui?.csp})}function ce(s){const e=B.c(37),{resourceURI:t,toolInfo:n,toolInput:o,toolResult:c,displayMode:a,minHeight:i,maxHeight:u,client:l,onMessage:r,className:h}=s,C=a===void 0?"inline":a,D=i===void 0?150:i,H=u===void 0?600:u;let v;e[0]!==l||e[1]!==t?(v={client:l,uri:t,staleTime:3e4},e[0]=l,e[1]=t,e[2]=v):v=e[2];const{data:$}=z(v),T=oe($);let y;e[3]!==l||e[4]!==C||e[5]!==H||e[6]!==D||e[7]!==r||e[8]!==n||e[9]!==o||e[10]!==c?(y={client:l,displayMode:C,minHeight:D,maxHeight:H,toolInfo:n,toolInput:o,toolResult:c,onMessage:r},e[3]=l,e[4]=C,e[5]=H,e[6]=D,e[7]=r,e[8]=n,e[9]=o,e[10]=c,e[11]=y):y=e[11];const{height:O,isLoading:R,error:I,iframeRef:P}=se(y);if(!T)return null;if(I){let w;e[12]!==h?(w=S("flex items-center justify-center p-4 text-destructive bg-destructive/10 rounded-lg",h),e[12]=h,e[13]=w):w=e[13];let x;e[14]!==I?(x=d.jsx("span",{className:"text-sm",children:I}),e[14]=I,e[15]=x):x=e[15];let j;return e[16]!==w||e[17]!==x?(j=d.jsx("div",{className:w,children:x}),e[16]=w,e[17]=x,e[18]=j):j=e[18],j}const _=n?.tool.name;let f;e[19]!==h?(f=S("relative w-full overflow-hidden rounded-lg",h),e[19]=h,e[20]=f):f=e[20];const A=`${O}px`;let m;e[21]!==A?(m={height:A},e[21]=A,e[22]=m):m=e[22];let p;e[23]!==R?(p=R&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background z-10",children:d.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[d.jsx("div",{className:"size-4 border-2 border-current border-t-transparent rounded-full animate-spin"}),d.jsx("span",{className:"text-sm",children:"Loading app..."})]})}),e[23]=R,e[24]=p):p=e[24];const k=R&&"invisible";let g;e[25]!==k?(g=S("w-full h-full border-0",k),e[25]=k,e[26]=g):g=e[26];const E=`MCP App: ${_??t}`;let b;e[27]!==T||e[28]!==P||e[29]!==g||e[30]!==E?(b=d.jsx("iframe",{ref:P,srcDoc:T,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups",className:g,title:E}),e[27]=T,e[28]=P,e[29]=g,e[30]=E,e[31]=b):b=e[31];let M;return e[32]!==b||e[33]!==f||e[34]!==m||e[35]!==p?(M=d.jsxs("div",{className:f,style:m,children:[p,b]}),e[32]=b,e[33]=f,e[34]=m,e[35]=p,e[36]=M):M=e[36],M}export{ce as M};
