import{r as _,c as V,v as O,j as d}from"./index-oE_2MbI2.js";import{u as q}from"./decopilot-events-DV5WFiTr.js";import{K as Y,T as G,t as J}from"./types-CZfjx8QG.js";function N(o){return Math.ceil(o.length*3/4)}function be(o){const e=[];for(const t of o)switch(t.type){case"text":t.text?.trim()&&e.push({type:"paragraph",content:[{type:"text",text:t.text}]});break;case"image":case"audio":t.data&&t.mimeType&&e.push({type:"paragraph",content:[{type:"file",attrs:{id:crypto.randomUUID(),name:`${t.type}.${t.mimeType.split("/")[1]??"bin"}`,mimeType:t.mimeType,size:N(t.data),data:t.data}}]});break;case"resource":{const n=t.resource;"text"in n&&n.text?e.push({type:"paragraph",content:[{type:"text",text:n.text}]}):"blob"in n&&n.blob&&e.push({type:"paragraph",content:[{type:"file",attrs:{id:crypto.randomUUID(),name:String(n.uri),mimeType:n.mimeType??"application/octet-stream",size:N(n.blob),data:n.blob}}]});break}case"resource_link":e.push({type:"paragraph",content:[{type:"text",text:t.name??t.uri}]});break}return{type:"doc",content:e}}const z=["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 Q(o,e={}){const n=`<meta http-equiv="Content-Security-Policy" content="${ee(e)}">`,s=/<head(\s[^>]*)?>|<HEAD(\s[^>]*)?>/i,c=o.match(s);if(c){const i=(c.index??0)+c[0].length;return o.slice(0,i)+`
`+n+o.slice(i)}const a=/<html(\s[^>]*)?>|<HTML(\s[^>]*)?>/i,r=o.match(a);if(r){const i=(r.index??0)+r[0].length;return o.slice(0,i)+`
<head>
`+n+`
</head>`+o.slice(i)}const u=/<!DOCTYPE[^>]*>/i,l=o.match(u);if(l){const i=(l.index??0)+l[0].length;return o.slice(0,i)+`
<head>
`+n+`
</head>`+o.slice(i)}return`<head>
`+n+`
</head>
`+o}const X=/^https?:\/\/(\*\.)?[a-zA-Z0-9._-]+(:\d+)?\/?$/;function L(o){return!o||o.length===0?[]:o.filter(e=>X.test(e))}function ee(o){if(o.csp)return o.csp;const e=o.resourceCsp;if(!e)return z;const t=L(e.resourceDomains),n=L(e.connectDomains),s=L(e.frameDomains),c=L(e.baseUriDomains),a=t.length>0,r=n.length>0,u=s.length>0,l=c.length>0;if(!a&&!r&&!u&&!l)return z;const i=t.join(" ");return["default-src 'none'",a?`script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' ${i}`:"script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval'",a?`style-src 'unsafe-inline' ${i}`:"style-src 'unsafe-inline'",a?`img-src * data: blob: ${i}`:"img-src * data: blob:",a?`font-src data: ${i}`:"font-src data:",r?`connect-src ${n.join(" ")}`:"connect-src 'none'",u?`frame-src ${s.join(" ")}`:"frame-src 'none'","worker-src blob:","form-action 'none'",l?`base-uri ${c.join(" ")}`:"base-uri 'none'"].join("; ")}const te=[["--background","--color-background-primary"],["--muted","--color-background-secondary"],["--accent","--color-background-tertiary"],["--destructive","--color-background-danger"],["--success","--color-background-success"],["--warning","--color-background-warning"],["--foreground","--color-text-primary"],["--muted-foreground","--color-text-secondary"],["--accent-foreground","--color-text-tertiary"],["--destructive-foreground","--color-text-danger"],["--success-foreground","--color-text-success"],["--warning-foreground","--color-text-warning"],["--border","--color-border-primary"],["--input","--color-border-secondary"],["--ring","--color-ring-primary"],["--font-sans","--font-sans"],["--font-mono","--font-mono"],["--font-weight-normal","--font-weight-normal"],["--font-weight-medium","--font-weight-medium"],["--font-weight-semibold","--font-weight-semibold"],["--font-weight-bold","--font-weight-bold"],["--radius","--border-radius-md"],["--default-border-width","--border-width-regular"],["--shadow-sm","--shadow-sm"],["--shadow-md","--shadow-md"],["--shadow-lg","--shadow-lg"]];function ne(){if(typeof document>"u")return{};const o=getComputedStyle(document.documentElement),e={};for(const[t,n]of te){const s=o.getPropertyValue(t).trim();s&&(e[n]=s)}return{variables:e}}const oe={name:"MCP Mesh",version:"1.0.0"},se={openLinks:{},serverTools:{},serverResources:{},logging:{},message:{},downloadFile:{},updateModelContext:{text:{}}},re=15e3;function ie(){return typeof navigator>"u"?"en":navigator.language??"en"}function ae(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}function ce(){return typeof navigator>"u"?"web":/Mobi|Android/i.test(navigator.userAgent)?"mobile":"web"}function B(o,e,t){return{theme:J(),styles:ne(),displayMode:o,availableDisplayModes:["inline","fullscreen"],locale:ie(),timeZone:ae(),platform:ce(),...e!=null&&{toolInfo:e},...t!=null&&{containerDimensions:{maxHeight:t}}}}const $=new Set;let F=!1;function le(){if(F||typeof document>"u")return;F=!0;const o=()=>$.forEach(e=>e());new MutationObserver(o).observe(document.documentElement,{attributes:!0,attributeFilter:["class","data-theme"]}),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",o)}function ue(o){return $.add(o),le(),()=>$.delete(o)}class de{bridge=null;timeout=null;disposed=!1;unsubTheme=null;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))}pushHostContext(){if(!this.bridge||this.disposed)return;const{displayMode:e,maxHeight:t,toolInfo:n}=this.config;this.bridge.setHostContext(B(e,n,t))}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 s of this.listeners)s()}}teardown(){(this.bridge||this.timeout||this.unsubTheme)&&this.config.onTeardown?.(),this.disposed=!0,this.unsubTheme?.(),this.unsubTheme=null,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:s,toolInfo:c}=this.config,a=B(n,c,s),r=new Y(t,oe,se,{hostContext:a});this.bridge=r,this.registerHandlers(r),this.startInitTimeout(),this.registerInitHandler(r),this.connectTransport(r,e),this.unsubTheme=ue(()=>this.pushHostContext())}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.onupdatemodelcontext=async t=>(this.config.onUpdateModelContext?.(t),{}),e.onsizechange=({height:t})=>{if(!this.disposed&&t!=null){const{minHeight:n,maxHeight:s}=this.config;this.set({height:Math.max(n,Math.min(s,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 s=n.resource,c="blob"in s?new Blob([Uint8Array.from(atob(s.blob),u=>u.charCodeAt(0))],{type:s.mimeType}):new Blob([s.text??""],{type:s.mimeType}),a=URL.createObjectURL(c),r=document.createElement("a");r.href=a,r.download=s.uri.split("/").pop()??"download",r.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})},re)}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 G(t.contentWindow,t.contentWindow);e.connect(n).catch(s=>{this.disposed||(this.clearTimeout(),console.error("AppBridge connect failed:",s),this.set({error:s instanceof Error?s.message:"Connection failed",isLoading:!1}))})}}function he(o){const e=_.useRef(new de(o));_.useEffect(()=>{e.current.updateConfig(o)},[o]);const{height:t,isLoading:n,error:s}=_.useSyncExternalStore(e.current.subscribe,e.current.getSnapshot);return{height:t,isLoading:n,error:s,iframeRef:e.current.attach}}function fe(o){const e=o?.contents?.[0];return!e||!("text"in e)||!e.text?null:Q(e.text,{resourceCsp:e._meta?.ui?.csp})}function ye(o){const e=V.c(39),{resourceURI:t,toolInfo:n,toolInput:s,toolResult:c,displayMode:a,minHeight:r,maxHeight:u,client:l,onMessage:i,onUpdateModelContext:x,onTeardown:D,className:h}=o,H=a===void 0?"inline":a,j=r===void 0?150:r,S=u===void 0?600:u;let T;e[0]!==l||e[1]!==t?(T={client:l,uri:t,staleTime:3e4},e[0]=l,e[1]=t,e[2]=T):T=e[2];const{data:W}=q(T),v=fe(W);let R;e[3]!==l||e[4]!==H||e[5]!==S||e[6]!==j||e[7]!==i||e[8]!==D||e[9]!==x||e[10]!==n||e[11]!==s||e[12]!==c?(R={client:l,displayMode:H,minHeight:j,maxHeight:S,toolInfo:n,toolInput:s,toolResult:c,onMessage:i,onUpdateModelContext:x,onTeardown:D},e[3]=l,e[4]=H,e[5]=S,e[6]=j,e[7]=i,e[8]=D,e[9]=x,e[10]=n,e[11]=s,e[12]=c,e[13]=R):R=e[13];const{height:Z,isLoading:M,error:C,iframeRef:P}=he(R);if(!v)return null;if(C){let y;e[14]!==h?(y=O("flex items-center justify-center p-4 text-destructive bg-destructive/10 rounded-lg",h),e[14]=h,e[15]=y):y=e[15];let w;e[16]!==C?(w=d.jsx("span",{className:"text-sm",children:C}),e[16]=C,e[17]=w):w=e[17];let I;return e[18]!==y||e[19]!==w?(I=d.jsx("div",{className:y,children:w}),e[18]=y,e[19]=w,e[20]=I):I=e[20],I}const K=n?.tool.name;let f;e[21]!==h?(f=O("relative w-full overflow-hidden rounded-lg",h),e[21]=h,e[22]=f):f=e[22];const U=`${Z}px`;let m;e[23]!==U?(m={height:U},e[23]=U,e[24]=m):m=e[24];let p;e[25]!==M?(p=M&&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[25]=M,e[26]=p):p=e[26];const E=M&&"invisible";let g;e[27]!==E?(g=O("w-full h-full border-0",E),e[27]=E,e[28]=g):g=e[28];const A=`MCP App: ${K??t}`;let b;e[29]!==v||e[30]!==P||e[31]!==g||e[32]!==A?(b=d.jsx("iframe",{ref:P,srcDoc:v,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups",className:g,title:A}),e[29]=v,e[30]=P,e[31]=g,e[32]=A,e[33]=b):b=e[33];let k;return e[34]!==b||e[35]!==f||e[36]!==m||e[37]!==p?(k=d.jsxs("div",{className:f,style:m,children:[p,b]}),e[34]=b,e[35]=f,e[36]=m,e[37]=p,e[38]=k):k=e[38],k}export{ye as M,be as c};
