@waniwani/sdk 0.11.13 → 0.11.14

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,2 +1,69 @@
1
- var T="text/html+skybridge",C="text/html;profile=mcp-app",S=async(e,o)=>{let t=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${t}${o}`)).text()};function M(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function _(e){let o=e.widgetCSP?{connectDomains:e.widgetCSP.connect_domains,resourceDomains:e.widgetCSP.resource_domains,frameDomains:e.widgetCSP.frame_domains,redirectDomains:e.widgetCSP.redirect_domains}:void 0;return{ui:{...o&&{csp:o},...e.widgetDomain&&{domain:e.widgetDomain},...e.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function x(e){return{...e.openaiTemplateUri&&{"openai/outputTemplate":e.openaiTemplateUri},"openai/toolInvocation/invoking":e.invoking,"openai/toolInvocation/invoked":e.invoked,"openai/widgetAccessible":!0,"openai/resultCanProduceWidget":!0,...e.mcpTemplateUri&&{ui:{resourceUri:e.mcpTemplateUri,...e.autoHeight&&{autoHeight:!0}}},...e.mcpTemplateUri&&{"ui/resourceUri":e.mcpTemplateUri}}}function h(e){let{id:o,title:t,description:a,baseUrl:p,htmlPath:y,widgetDomain:c,prefersBorder:n=!0,autoHeight:d=!0}=e,i=e.widgetCSP??{connect_domains:[p],resource_domains:[p]};if(process.env.NODE_ENV==="development")try{let{hostname:r}=new URL(p);(r==="localhost"||r==="127.0.0.1")&&(i={...i,connect_domains:[...i.connect_domains||[],`ws://${r}:*`,`wss://${r}:*`],resource_domains:[...i.resource_domains||[],`http://${r}:*`]})}catch{}let g=`ui://widgets/apps-sdk/${o}.html`,w=`ui://widgets/ext-apps/${o}.html`,u=null,f=()=>(u||(u=S(p,y)),u),s=a;async function P(r){let R=await f();r.registerResource(`${o}-openai-widget`,g,{title:t,description:s,mimeType:T,_meta:{"openai/widgetDescription":s,"openai/widgetPrefersBorder":n}},async k=>({contents:[{uri:k.href,mimeType:T,text:R,_meta:M({description:s,prefersBorder:n,widgetDomain:c,widgetCSP:i})}]})),r.registerResource(`${o}-mcp-widget`,w,{title:t,description:s,mimeType:C,_meta:{ui:{prefersBorder:n}}},async k=>({contents:[{uri:k.href,mimeType:C,text:R,_meta:_({description:s,prefersBorder:n,widgetDomain:c,widgetCSP:i})}]}))}return{id:o,title:t,description:a,openaiUri:g,mcpUri:w,autoHeight:d,register:P}}var I="waniwani/client";function v(e){if(typeof e=="object"&&e!==null)return e[I]}function E(e,o){let{resource:t,description:a,inputSchema:p,annotations:y,autoInjectResultText:c=!0}=e,n=e.id??t?.id,d=e.title??t?.title;if(!n)throw new Error("createTool: `id` is required when no resource is provided");if(!d)throw new Error("createTool: `title` is required when no resource is provided");let i=t?x({openaiTemplateUri:t.openaiUri,mcpTemplateUri:t.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:t.autoHeight}):void 0;return{id:n,title:d,description:a,async register(g){g.registerTool(n,{title:d,description:a,inputSchema:p,annotations:y,...i&&{_meta:i}},(async(w,u)=>{let f=u,s=f._meta??{},P=v(f),r=await o(w,{extra:{_meta:s},waniwani:P});return t&&r.data?{content:[{type:"text",text:r.text}],structuredContent:r.data,_meta:{...i,...s,...c===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:r.text}],...r.data?{structuredContent:r.data}:{},...c===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function b(e,o){await Promise.all(o.map(t=>t.register(e)))}export{h as createResource,E as createTool,b as registerTools};
1
+ import{a as se,b as Ze,c as Qe}from"../chunk-F4KBGLBK.js";import{b as $,c as Q,e as pe}from"../chunk-BZRGY3DY.js";var ee="text/html+skybridge",te="text/html;profile=mcp-app",ue=async(e,t)=>{let r=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${r}${t}`)).text()};function me(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function ge(e){let t=e.widgetCSP?{connectDomains:e.widgetCSP.connect_domains,resourceDomains:e.widgetCSP.resource_domains,frameDomains:e.widgetCSP.frame_domains,redirectDomains:e.widgetCSP.redirect_domains}:void 0;return{ui:{...t&&{csp:t},...e.widgetDomain&&{domain:e.widgetDomain},...e.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function ie(e){return{...e.openaiTemplateUri&&{"openai/outputTemplate":e.openaiTemplateUri},"openai/toolInvocation/invoking":e.invoking,"openai/toolInvocation/invoked":e.invoked,"openai/widgetAccessible":!0,"openai/resultCanProduceWidget":!0,...e.mcpTemplateUri&&{ui:{resourceUri:e.mcpTemplateUri,...e.autoHeight&&{autoHeight:!0}}},...e.mcpTemplateUri&&{"ui/resourceUri":e.mcpTemplateUri}}}function fe(e){let{id:t,title:r,description:c,baseUrl:s,htmlPath:p,widgetDomain:g,prefersBorder:u=!0,autoHeight:a=!0}=e,i=e.widgetCSP??{connect_domains:[s],resource_domains:[s]};if(process.env.NODE_ENV==="development")try{let{hostname:y}=new URL(s);(y==="localhost"||y==="127.0.0.1")&&(i={...i,connect_domains:[...i.connect_domains||[],`ws://${y}:*`,`wss://${y}:*`],resource_domains:[...i.resource_domains||[],`http://${y}:*`]})}catch{}let o=`ui://widgets/apps-sdk/${t}.html`,l=`ui://widgets/ext-apps/${t}.html`,n=null,w=()=>(n||(n=ue(s,p)),n),m=c;async function x(y){let M=await w();y.registerResource(`${t}-openai-widget`,o,{title:r,description:m,mimeType:ee,_meta:{"openai/widgetDescription":m,"openai/widgetPrefersBorder":u}},async T=>({contents:[{uri:T.href,mimeType:ee,text:M,_meta:me({description:m,prefersBorder:u,widgetDomain:g,widgetCSP:i})}]})),y.registerResource(`${t}-mcp-widget`,l,{title:r,description:m,mimeType:te,_meta:{ui:{prefersBorder:u}}},async T=>({contents:[{uri:T.href,mimeType:te,text:M,_meta:ge({description:m,prefersBorder:u,widgetDomain:g,widgetCSP:i})}]}))}return{id:t,title:r,description:c,openaiUri:o,mcpUri:l,autoHeight:a,register:x}}var et="waniwani/client";function he(e){if(typeof e=="object"&&e!==null)return e[et]}function tt(e,t){let{resource:r,description:c,inputSchema:s,annotations:p,autoInjectResultText:g=!0}=e,u=e.id??r?.id,a=e.title??r?.title;if(!u)throw new Error("createTool: `id` is required when no resource is provided");if(!a)throw new Error("createTool: `title` is required when no resource is provided");let i=r?ie({openaiTemplateUri:r.openaiUri,mcpTemplateUri:r.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:r.autoHeight}):void 0;return{id:u,title:a,description:c,async register(o){o.registerTool(u,{title:a,description:c,inputSchema:s,annotations:p,...i&&{_meta:i}},(async(l,n)=>{let w=n,m=w._meta??{},x=he(w),y=await t(l,{extra:{_meta:m},waniwani:x});return r&&y.data?{content:[{type:"text",text:y.text}],structuredContent:y.data,_meta:{...i,...m,...g===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:y.text}],...y.data?{structuredContent:y.data}:{},...g===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function ot(e,t){await Promise.all(t.map(r=>r.register(e)))}import{Fragment as it,jsx as z,jsxs as at}from"react/jsx-runtime";function rt(){let e=window.innerBaseUrl,t=window.__wwPassthroughOrigins??[],r=document.documentElement;new MutationObserver(a=>{a.forEach(i=>{if(i.type==="attributes"&&i.target===r){let o=i.attributeName;o&&o!=="suppresshydrationwarning"&&o!=="lang"&&o!=="class"&&o!=="style"&&r.removeAttribute(o)}})}).observe(r,{attributes:!0,attributeOldValue:!0});let s=history.replaceState.bind(history);history.replaceState=(a,i,o)=>{try{let l=new URL(String(o??""),window.location.href);s(null,i,l.pathname+l.search+l.hash)}catch{}};let p=history.pushState.bind(history);history.pushState=(a,i,o)=>{try{let l=new URL(String(o??""),window.location.href);p(null,i,l.pathname+l.search+l.hash)}catch{}};let g=new URL(e).origin,u=window.self!==window.top;if(window.addEventListener("click",a=>{let i=a?.target?.closest("a");if(!i||!i.href)return;let o=new URL(i.href,window.location.href);if(o.origin!==window.location.origin&&o.origin!==g)try{window.openai&&(window.openai?.openExternal({href:i.href}),a.preventDefault())}catch{console.warn("openExternal failed, likely not in OpenAI client")}},!0),u&&window.location.origin!==g){let a=window.fetch;window.fetch=((n,w)=>{let m=typeof n=="string"&&!/^[a-z][a-z0-9+.-]*:/i.test(n)&&!n.startsWith("//"),x;if(typeof n=="string"||n instanceof URL?x=new URL(n,window.location.href):x=new URL(n.url,window.location.href),x.origin===g)return typeof n=="string"||n instanceof URL?n=x.toString():n=new Request(x.toString(),n),a.call(window,n,{...w,mode:"cors"});if(t.indexOf(x.origin)!==-1)return a.call(window,n,w);if(m&&x.origin===window.location.origin){let y=new URL(e);return y.pathname=x.pathname,y.search=x.search,y.hash=x.hash,x=y,n=x.toString(),a.call(window,n,{...w,mode:"cors"})}return a.call(window,n,w)});let i=g.replace(/^http/,"ws"),o=window.WebSocket,l=((n,w)=>{let m=new URL(String(n),window.location.href);if(m.origin===window.location.origin||m.origin===window.location.origin.replace(/^http/,"ws")){let x=new URL(i);return x.pathname=m.pathname,x.search=m.search,x.hash=m.hash,new o(x.toString(),w)}return new o(n,w)});l.prototype=o.prototype,Object.assign(l,{CONNECTING:o.CONNECTING,OPEN:o.OPEN,CLOSING:o.CLOSING,CLOSED:o.CLOSED}),window.WebSocket=l}}var nt=`(${rt.toString()})()`;function st({baseUrl:e,passthroughOrigins:t}){return at(it,{children:[z("base",{href:e}),z("script",{children:`window.innerBaseUrl = ${JSON.stringify(e)}`}),z("script",{children:`window.__wwPassthroughOrigins = ${JSON.stringify(t??[])}`}),z("script",{children:'window.__isChatGptApp = typeof window.openai !== "undefined";'}),z("script",{children:nt})]})}import{useCallback as L,useEffect as G,useRef as ae,useState as H}from"react";var we={theme:"dark",userAgent:{device:{type:"desktop"},capabilities:{hover:!0,touch:!1}},locale:"en",maxHeight:800,displayMode:"inline",safeArea:{insets:{top:0,bottom:0,left:0,right:0}},toolInput:{},toolOutput:null,toolResponseMetadata:null,widgetState:null},K={...we};function J(e){typeof window>"u"||window.openai||(K={...we,toolOutput:e??null},window.openai={...K,requestDisplayMode:async({mode:t})=>(F("displayMode",t),{mode:t}),callTool:async(t,r)=>(console.log(`[DevMode] callTool: ${t}`,r),{result:JSON.stringify({mock:!0,tool:t,args:r})}),sendFollowUpMessage:async({prompt:t})=>{console.log(`[DevMode] sendFollowUpMessage: ${t}`)},openExternal:({href:t})=>{console.log(`[DevMode] openExternal: ${t}`),window.open(t,"_blank")},setWidgetState:async t=>{F("widgetState",t)}},window.dispatchEvent(new $({globals:K})))}function F(e,t){typeof window>"u"||!window.openai||(K[e]=t,window.openai[e]=t,window.dispatchEvent(new $({globals:{[e]:t}})))}function oe(){return{...K}}function V(e){F("toolOutput",e)}function Y(e){F("displayMode",e)}function X(e){F("theme",e)}import{Fragment as le,jsx as d,jsxs as S}from"react/jsx-runtime";var re=150;function xe({className:e}){return S("svg",{className:e,viewBox:"0 0 24 24",fill:"none",role:"img","aria-label":"Dev Controls",children:[d("rect",{x:"4",y:"4",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5"}),d("rect",{x:"10",y:"10",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5",fill:"currentColor",fillOpacity:"0.15"})]})}function lt({className:e}){return d("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M18 6L6 18M6 6l12 12"})})}function ct({className:e}){return d("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:d("rect",{x:"2",y:"4",width:"12",height:"8",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"})})}function dt({className:e}){return S("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[d("rect",{x:"1.5",y:"3",width:"13",height:"10",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"}),d("rect",{x:"8.5",y:"7",width:"5",height:"4",rx:"0.75",fill:"currentColor"})]})}function pt({className:e}){return d("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:d("path",{d:"M2 5.5V3.5C2 2.95 2.45 2.5 3 2.5H5.5M10.5 2.5H13C13.55 2.5 14 2.95 14 3.5V5.5M14 10.5V12.5C14 13.05 13.55 13.5 13 13.5H10.5M5.5 13.5H3C2.45 13.5 2 13.05 2 12.5V10.5",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})}function ut({className:e}){return S("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[d("circle",{cx:"8",cy:"8",r:"2.5",stroke:"currentColor",strokeWidth:"1.25"}),d("path",{d:"M8 2v1.5M8 12.5V14M2 8h1.5M12.5 8H14M4.11 4.11l1.06 1.06M10.83 10.83l1.06 1.06M4.11 11.89l1.06-1.06M10.83 5.17l1.06-1.06",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]})}function mt({className:e}){return d("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:d("path",{d:"M13.5 9.5a5.5 5.5 0 01-7-7 5.5 5.5 0 107 7z",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})}function gt({className:e}){return S("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[d("path",{d:"M2.5 8a5.5 5.5 0 019.37-3.9M13.5 8a5.5 5.5 0 01-9.37 3.9",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"}),d("path",{d:"M12.5 2v3h-3M3.5 14v-3h3",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})]})}var ft=`
2
+ @keyframes devPanelSlideIn {
3
+ 0% {
4
+ opacity: 0;
5
+ transform: translateY(12px) scale(0.98);
6
+ }
7
+ 100% {
8
+ opacity: 1;
9
+ transform: translateY(0) scale(1);
10
+ }
11
+ }
12
+
13
+ @keyframes devPanelSlideOut {
14
+ 0% {
15
+ opacity: 1;
16
+ transform: translateY(0) scale(1);
17
+ }
18
+ 100% {
19
+ opacity: 0;
20
+ transform: translateY(8px) scale(0.98);
21
+ }
22
+ }
23
+
24
+ .dev-panel-enter {
25
+ animation: devPanelSlideIn 200ms cubic-bezier(0.16, 1, 0.3, 1) forwards;
26
+ }
27
+
28
+ .dev-panel-exit {
29
+ animation: devPanelSlideOut 150ms cubic-bezier(0.4, 0, 1, 1) forwards;
30
+ }
31
+
32
+ .dev-json-editor::-webkit-scrollbar {
33
+ width: 6px;
34
+ height: 6px;
35
+ }
36
+
37
+ .dev-json-editor::-webkit-scrollbar-track {
38
+ background: transparent;
39
+ }
40
+
41
+ .dev-json-editor::-webkit-scrollbar-thumb {
42
+ background: rgba(255, 255, 255, 0.1);
43
+ border-radius: 3px;
44
+ }
45
+
46
+ .dev-json-editor::-webkit-scrollbar-thumb:hover {
47
+ background: rgba(255, 255, 255, 0.15);
48
+ }
49
+ `;function be({defaultProps:e,widgetPaths:t,children:r}){let[c,s]=H(!1),[p,g]=H(!1);return G(()=>{if(new URLSearchParams(window.location.search).get("platform")==="mcp-apps"){s(!0);return}if(t&&t.length>0){let a=window.location.pathname,i=t.some(o=>a===o||a.startsWith(`${o}/`));g(i),i&&J(e)}else J(e),g(!0);s(!0)},[e,t]),c?p?S(le,{children:[d(ht,{children:r}),d(wt,{defaultProps:e})]}):d(le,{children:r}):null}function ht({children:e}){return d("div",{className:"min-h-screen bg-[#212121] flex items-center justify-center p-8",children:d("div",{className:"relative w-full max-w-md overflow-hidden rounded-2xl sm:rounded-3xl border border-[#414141]",style:{boxShadow:"0px 0px 0px 1px #414141, 0px 4px 14px rgba(0,0,0,0.24)"},children:e})})}function ye({options:e,value:t,onChange:r}){let c=e.findIndex(s=>s.value===t);return S("div",{className:"relative flex p-0.5 rounded-lg",style:{background:"rgba(255, 255, 255, 0.04)",border:"1px solid rgba(255, 255, 255, 0.06)"},children:[d("div",{className:"absolute top-0.5 bottom-0.5 rounded-md transition-transform duration-150 ease-out",style:{width:`calc(${100/e.length}% - 2px)`,left:"2px",transform:`translateX(calc(${c*100}% + ${c*2}px))`,background:"rgba(255, 255, 255, 0.1)"}}),e.map(s=>S("button",{type:"button",onClick:()=>r(s.value),className:`
50
+ relative z-10 flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5
51
+ text-xs font-medium rounded-md transition-colors duration-150
52
+ ${t===s.value?"text-white":"text-gray-400 hover:text-gray-300"}
53
+ `,children:[s.icon,d("span",{className:"capitalize",children:s.label})]},s.value))]})}function wt({defaultProps:e}){let[t,r]=H(()=>typeof window>"u"?!1:localStorage.getItem("dev-controls-open")==="true"),[c,s]=H(!1),[p,g]=H(t),[u,a]=H("inline"),[i,o]=H("dark"),[l,n]=H(!1),[w,m]=H(()=>JSON.stringify(e??{},null,2)),[x,y]=H(null),M=ae(null),T=ae(null),j=ae(null);G(()=>{let b=oe();a(b.displayMode),o(b.theme)},[]),G(()=>{typeof window>"u"||(window.openai||(window.openai={}),window.openai.safeArea={insets:{top:0,bottom:l?re:0,left:0,right:0}},window.dispatchEvent(new $({globals:{safeArea:window.openai.safeArea}})))},[l]),G(()=>{localStorage.setItem("dev-controls-open",String(t))},[t]);let q=L(()=>{g(!0),requestAnimationFrame(()=>{r(!0)})},[]),N=L(()=>{s(!0),r(!1),setTimeout(()=>{g(!1),s(!1)},150)},[]),_=L(()=>{t?N():q()},[t,q,N]);G(()=>{let b=E=>{(E.metaKey||E.ctrlKey)&&E.shiftKey&&E.key==="d"&&(E.preventDefault(),_()),E.key==="Escape"&&t&&N()};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[t,_,N]),G(()=>{if(!t)return;let b=E=>{j.current&&!j.current.contains(E.target)&&N()};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[t,N]);let O=L(b=>{a(b),Y(b)},[]),R=L(b=>{o(b),X(b)},[]),U=L(b=>{try{let E=JSON.parse(b);y(null),V(E)}catch{y("Invalid JSON")}},[]),C=L(b=>{m(b),M.current&&clearTimeout(M.current),M.current=setTimeout(()=>{U(b)},500)},[U]),A=L(()=>{M.current&&clearTimeout(M.current),U(w)},[U,w]),P=L(()=>{let b=JSON.stringify(e??{},null,2);m(b),y(null),V(e??{}),a("inline"),Y("inline"),o("dark"),X("dark")},[e]),v=[{value:"inline",label:"inline",icon:d(ct,{className:"w-3.5 h-3.5"})},{value:"pip",label:"pip",icon:d(dt,{className:"w-3.5 h-3.5"})},{value:"fullscreen",label:"full",icon:d(pt,{className:"w-3.5 h-3.5"})}],I=[{value:"light",label:"light",icon:d(ut,{className:"w-3.5 h-3.5"})},{value:"dark",label:"dark",icon:d(mt,{className:"w-3.5 h-3.5"})}];return S(le,{children:[d("style",{dangerouslySetInnerHTML:{__html:ft}}),S("div",{ref:j,className:"fixed bottom-4 right-4 z-[9999] font-['Inter',_system-ui,_sans-serif]",children:[S("button",{type:"button",onClick:_,className:"group relative flex items-center justify-center w-11 h-11 rounded-xl transition-all duration-200 ease-out hover:scale-105 active:scale-95",style:{background:"rgba(14, 14, 16, 0.95)",backdropFilter:"blur(16px)",WebkitBackdropFilter:"blur(16px)",border:"1px solid rgba(255, 255, 255, 0.08)",boxShadow:`
54
+ 0 4px 12px rgba(0, 0, 0, 0.4),
55
+ 0 0 0 1px rgba(255, 255, 255, 0.05),
56
+ inset 0 1px 0 rgba(255, 255, 255, 0.04)
57
+ `},"aria-label":"Toggle Dev Controls","aria-expanded":t,children:[d(xe,{className:`w-5 h-5 transition-all duration-200 ${t?"text-indigo-400 scale-110":"text-gray-300 group-hover:text-white"}`}),d("div",{className:"absolute inset-0 rounded-xl opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none",style:{background:"radial-gradient(circle at center, rgba(99, 102, 241, 0.15) 0%, transparent 70%)"}})]}),p&&S("div",{ref:T,className:`absolute bottom-14 right-0 w-80 ${t&&!c?"dev-panel-enter":"dev-panel-exit"}`,style:{maxHeight:"calc(100vh - 120px)",background:"rgba(14, 14, 16, 0.92)",backdropFilter:"blur(24px)",WebkitBackdropFilter:"blur(24px)",border:"1px solid rgba(255, 255, 255, 0.06)",borderRadius:"16px",boxShadow:`
58
+ 0 25px 50px -12px rgba(0, 0, 0, 0.6),
59
+ 0 0 0 1px rgba(255, 255, 255, 0.05),
60
+ inset 0 1px 0 rgba(255, 255, 255, 0.04)
61
+ `},children:[S("div",{className:"flex items-center justify-between px-4 py-3",style:{borderBottom:"1px solid rgba(255, 255, 255, 0.06)"},children:[S("div",{className:"flex items-center gap-2",children:[d(xe,{className:"w-4 h-4 text-gray-400"}),d("span",{className:"text-sm font-medium text-white",children:"Dev Controls"})]}),S("div",{className:"flex items-center gap-2",children:[d("span",{className:"text-[10px] font-medium text-gray-500 px-1.5 py-0.5 rounded",style:{background:"rgba(255, 255, 255, 0.04)",border:"1px solid rgba(255, 255, 255, 0.06)"},children:typeof navigator<"u"&&navigator.platform?.includes("Mac")?"\u2318\u21E7D":"Ctrl+Shift+D"}),d("button",{type:"button",onClick:N,className:"p-1 rounded-md text-gray-500 hover:text-gray-300 hover:bg-white/5 transition-colors",children:d(lt,{className:"w-4 h-4"})})]})]}),S("div",{className:"p-4 space-y-5 overflow-y-auto",style:{maxHeight:"calc(100vh - 200px)"},children:[S("div",{children:[d("label",{htmlFor:"display-mode",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Display Mode"}),d(ye,{options:v,value:u,onChange:O})]}),S("div",{children:[d("label",{htmlFor:"theme",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Theme"}),d(ye,{options:I,value:i,onChange:R})]}),S("div",{children:[d("label",{htmlFor:"safe-area",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Safe Area (Chat Input)"}),S("button",{type:"button",onClick:()=>n(!l),className:`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-xs font-medium transition-all duration-150 ${l?"text-emerald-400":"text-gray-400"}`,style:{background:l?"rgba(34, 197, 94, 0.1)":"rgba(255, 255, 255, 0.04)",border:l?"1px solid rgba(34, 197, 94, 0.3)":"1px solid rgba(255, 255, 255, 0.06)"},children:[d("span",{children:"Mock ChatGPT Input Bar"}),d("span",{className:`px-2 py-0.5 rounded text-[10px] font-semibold ${l?"bg-emerald-500/20 text-emerald-400":"bg-gray-500/20 text-gray-500"}`,children:l?"ON":"OFF"})]}),l&&S("p",{className:"text-[10px] text-gray-500 mt-1.5",children:["bottom: ",re,"px"]})]}),S("div",{children:[d("label",{htmlFor:"widget-props",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Widget Props"}),d("textarea",{value:w,onChange:b=>C(b.target.value),onBlur:A,className:"dev-json-editor w-full min-h-[160px] text-xs text-gray-200 p-3 rounded-lg resize-none focus:outline-none transition-colors",style:{background:"rgba(0, 0, 0, 0.3)",border:x?"1px solid rgba(239, 68, 68, 0.5)":"1px solid rgba(255, 255, 255, 0.06)",fontFamily:"'JetBrains Mono', 'SF Mono', 'Fira Code', monospace",lineHeight:1.6},onFocus:b=>{x||(b.target.style.borderColor="rgba(99, 102, 241, 0.5)")},onBlurCapture:b=>{x||(b.target.style.borderColor="rgba(255, 255, 255, 0.06)")},spellCheck:!1}),x&&S("p",{className:"text-red-400 text-[11px] mt-1.5 flex items-center gap-1",children:[d("svg",{"aria-hidden":"true","aria-label":"Error",className:"w-3 h-3",viewBox:"0 0 16 16",fill:"currentColor",children:d("path",{d:"M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM7 4.5h2v4H7v-4zm0 5h2v2H7v-2z"})}),x]})]}),S("button",{type:"button",onClick:P,className:"w-full flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-xs font-medium text-gray-400 transition-all duration-150 hover:text-gray-200",style:{background:"rgba(255, 255, 255, 0.04)",border:"1px solid rgba(255, 255, 255, 0.06)"},onMouseEnter:b=>{b.currentTarget.style.background="rgba(255, 255, 255, 0.08)",b.currentTarget.style.borderColor="rgba(255, 255, 255, 0.1)"},onMouseLeave:b=>{b.currentTarget.style.background="rgba(255, 255, 255, 0.04)",b.currentTarget.style.borderColor="rgba(255, 255, 255, 0.06)"},children:[d(gt,{className:"w-3.5 h-3.5"}),"Reset to Defaults"]})]})]})]}),l&&S("div",{className:"fixed bottom-0 left-0 right-0 z-[9998] flex items-center justify-center pointer-events-none",style:{height:`${re}px`,background:"linear-gradient(to top, #1a1a1a 0%, #1a1a1a 80%, transparent 100%)"},children:[S("div",{className:"w-full max-w-2xl mx-4 px-4 py-3 rounded-2xl bg-[#2f2f2f] border border-[#424242] flex items-center gap-3",children:[d("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:d("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:d("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),d("div",{className:"flex-1 text-gray-400 text-sm",children:"Ask me anything..."}),d("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:d("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:d("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"})})})]}),S("div",{className:"absolute bottom-1 text-[10px] text-gray-600 font-mono",children:["Mock SafeArea: bottom=",re,"px"]})]})]})}import{useCallback as vt}from"react";import Z,{useCallback as Ce,useContext as yt,useEffect as ke,useState as de,useSyncExternalStore as bt}from"react";import{createContext as xt}from"react";var ce=xt(null);async function ve(){let{detectPlatform:e}=await import("../platform-3OQJPJOZ.js");if(e()==="openai"){let{OpenAIWidgetClient:r}=await import("../openai-client-URAITCJJ.js");return new r}else{let{MCPAppsWidgetClient:r}=await import("../mcp-apps-client-GGRBZ3XV.js");return new r}}function Re({children:e,loading:t=null,onError:r}){let[c,s]=de(null),[p,g]=de(null),[u,a]=de(!0);return ke(()=>{let i=!0,o=null;async function l(){try{let n=await ve();await n.connect(),i?(o=n,s(n),a(!1)):n.close()}catch(n){i&&(console.error("error",n),g(n instanceof Error?n:new Error(String(n))),a(!1))}}return l(),()=>{i=!1,o?.close()}},[]),ke(()=>{if(!c)return;let i=o=>{document.documentElement.classList.toggle("dark",o==="dark"),document.documentElement.style.colorScheme=o==="dark"?"dark":"auto"};return i(c.getTheme()),c.onThemeChange(i)},[c]),p&&r?Z.createElement(Z.Fragment,null,r(p)):u||!c?Z.createElement(Z.Fragment,null,t):Z.createElement(ce.Provider,{value:c},e)}function k(e){let t=yt(ce);if(!t)throw new Error("useWidgetClient must be used within a WidgetProvider");let r=Ce(p=>e==="toolOutput"?t.onToolResult(()=>p()):e==="theme"?t.onThemeChange(()=>p()):e==="displayMode"?t.onDisplayModeChange(()=>p()):e==="safeArea"?t.onSafeAreaChange(()=>p()):e==="maxHeight"?t.onMaxHeightChange(()=>p()):e==="toolResponseMetadata"?t.onToolResponseMetadataChange(()=>p()):e==="widgetState"?t.onWidgetStateChange(()=>p()):()=>{},[t,e]),c=Ce(()=>e==="toolOutput"?t.getToolOutput():e==="theme"?t.getTheme():e==="displayMode"?t.getDisplayMode():e==="locale"?t.getLocale():e==="safeArea"?t.getSafeArea():e==="maxHeight"?t.getMaxHeight():e==="toolResponseMetadata"?t.getToolResponseMetadata():e==="widgetState"?t.getWidgetState():null,[t,e]),s=bt(r,c,c);return e?s:t}function Se(){let e=k();return vt((t,r)=>e.callTool(t,r),[e])}function Me(){return k("displayMode")}function ne(){return k("toolOutput")}function Te(){return{data:ne()}}import{useSyncExternalStore as Ct}from"react";function Pe(){return Ct(()=>()=>{},()=>typeof window>"u"?!1:window.__isChatGptApp===!0,()=>!1)}function Ue(){return k("locale")}function Oe(){return k("maxHeight")}import{useCallback as kt}from"react";function Ae(){let e=k();return kt(t=>e.openExternal(t),[e])}import{useCallback as Rt}from"react";function We(){let e=k();return Rt(t=>e.requestDisplayMode(t),[e])}function Ne(){return k("safeArea")}import{useCallback as St}from"react";function Ie(){let e=k();return St((t,r)=>{(async()=>{Q(r?.modelContext)&&await Promise.resolve(e.updateModelContext(r.modelContext)),await Promise.resolve(e.sendFollowUp(t))})().catch(c=>{console.error("Failed to send follow-up message:",c)})},[e])}function Ee(){return k("theme")}function He(){return k("toolResponseMetadata")}import{useCallback as Mt}from"react";function De(){let e=k();return Mt(async t=>{await Promise.resolve(e.updateModelContext(t))},[e])}import{useCallback as Tt,useEffect as Pt,useState as Ut}from"react";function Le(e){let t=k("widgetState"),[r,c]=Ut(()=>t??(typeof e=="function"?e():e??null));Pt(()=>{c(t)},[t]);let s=Tt(p=>{c(g=>{let u=typeof p=="function"?p(g):p;return se()==="openai"&&u!=null&&window.openai?.setWidgetState(u),u})},[]);return[r,s]}import{jsx as B,jsxs as je}from"react/jsx-runtime";var Ot=()=>je("div",{className:"flex flex-col items-center justify-center h-full min-h-[120px] gap-4",children:[je("div",{className:"flex gap-2",children:[B("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-blue-400 to-cyan-400 animate-bounce [animation-delay:-0.3s]"}),B("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-cyan-400 to-teal-400 animate-bounce [animation-delay:-0.15s]"}),B("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-teal-400 to-emerald-400 animate-bounce"})]}),B("p",{className:"text-sm font-medium text-transparent bg-clip-text bg-gradient-to-r from-slate-400 via-slate-200 to-slate-400 bg-[length:200%_100%] animate-[shimmer_1.5s_ease-in-out_infinite]",children:"Loading widget..."}),B("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:B("div",{className:"w-16 h-16 rounded-full border-2 border-blue-400/20 animate-ping"})}),B("style",{children:`
62
+ @keyframes shimmer {
63
+ 0% { background-position: 200% 0; }
64
+ 100% { background-position: -200% 0; }
65
+ }
66
+ `})]});var At={debug:0,warn:1,error:2,none:3};function Wt(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in At?e:process.env.WANIWANI_DEBUG?"debug":"none"}function D(e,t){return t??Wt()==="debug"?(...c)=>console.log(`[waniwani:${e}]`,...c):()=>{}}function _e(e){if(e===!0)return{};if(!(e===!1||e===void 0))return e}function Fe(){return function(t){return t.headers.set("Access-Control-Allow-Origin","*"),t.headers.set("Access-Control-Allow-Methods","GET, POST, PATCH, OPTIONS"),t.headers.set("Access-Control-Allow-Headers","Content-Type, Authorization, X-Session-Id, X-Client-User-Agent"),t.headers.set("Access-Control-Expose-Headers","X-Session-Id"),t}}function Be(e){return function(r,c){return e(new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"},status:c}))}}var W=class extends Error{constructor(r,c){super(r);this.status=c;this.name="WaniWaniError"}};function qe(e){let t=e.headers,r=t.get("x-vercel-ip-city")??t.get("cf-ipcity")??void 0,c=r?Nt(r):void 0,s=t.get("x-vercel-ip-country")??t.get("cf-ipcountry")??void 0,p=t.get("x-vercel-ip-country-region")??void 0,g=t.get("x-vercel-ip-latitude")??t.get("cf-iplatitude")??void 0,u=t.get("x-vercel-ip-longitude")??t.get("cf-iplongitude")??void 0,a=t.get("x-vercel-ip-timezone")??t.get("cf-iptimezone")??void 0,i=t.get("x-real-ip")??t.get("x-forwarded-for")?.split(",")[0]?.trim()??t.get("cf-connecting-ip")??void 0;return{city:c,country:s,countryRegion:p,latitude:g,longitude:u,timezone:a,ip:i}}function Nt(e){try{return decodeURIComponent(e)}catch{return e}}function Ge(e,t){if(!Q(t))return e;let r=pe(t);return r?[e,r].filter(Boolean).join(`
67
+
68
+ `):e}function $e(e){let{apiKey:t,apiUrl:r,source:c,systemPrompt:s,maxSteps:p,beforeRequest:g,mcpServerUrl:u,resolveConfig:a,debug:i,webSearch:o}=e,l=D("chat",i);return async function(w){l("\u2192 POST",w.url);try{let m=await w.json(),x=m.messages??[],y=m.sessionId,M=m.modelContext,T=s,j=typeof m.extra=="object"&&m.extra!==null&&!Array.isArray(m.extra)?m.extra:void 0,q=m.visitorContext??null,N=qe(w),_={geo:N,client:q};if(l("body parsed \u2014 messages:",x.length,"sessionId:",y??"(none)","geo:",JSON.stringify(N)),g){l("running beforeRequest hook");try{let v=await g({messages:x,sessionId:y,modelContext:M,request:w,visitor:_});v&&(v.messages&&(x=v.messages),v.systemPrompt!==void 0&&(T=v.systemPrompt),v.sessionId!==void 0&&(y=v.sessionId),v.modelContext!==void 0&&(M=v.modelContext)),l("beforeRequest hook done \u2014 messages:",x.length,"sessionId:",y??"(none)")}catch(v){console.error("[waniwani:chat] beforeRequest hook error:",v);let I=v instanceof W?v.status:400,b=v instanceof Error?v.message:"Request rejected";return l("\u2190 returning",I,"from hook error"),Response.json({error:b},{status:I})}}let O=u??(await a()).mcpServerUrl;l("mcpServerUrl:",O),T=Ge(T,M);let R=`${r}/api/mcp/chat`;l("forwarding to",R);let U=w.headers.get("user-agent"),C=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json","X-WaniWani-Stream-Protocol":"2",...t?{Authorization:`Bearer ${t}`}:{},...U?{"X-Client-User-Agent":U}:{}},body:JSON.stringify({messages:x,mcpServerUrl:O,sessionId:y,source:c,systemPrompt:T,maxSteps:p,visitor:_,webSearch:o,...j&&{extra:j}}),signal:w.signal});if(l("upstream response status:",C.status),!C.ok){let v=await C.text().catch(()=>"");return l("\u2190 returning",C.status,"upstream error:",v),new Response(v,{status:C.status,headers:{"Content-Type":C.headers.get("Content-Type")??"application/json"}})}let A=new Headers({"Content-Type":C.headers.get("Content-Type")??"text/event-stream"}),P=C.headers.get("x-session-id");return P&&A.set("x-session-id",P),l("\u2190 streaming response",C.status,"body null?",C.body===null),new Response(C.body,{status:C.status,headers:A})}catch(m){console.error("[waniwani:chat] handler error:",m);let x=m instanceof Error?m.message:"Unknown error occurred",y=m instanceof W?m.status:500;return l("\u2190 returning",y,"from caught error"),Response.json({error:x},{status:y})}}}function ze(e){let{mcpServerUrl:t,resolveConfig:r,debug:c}=e,s=D("resource",c);return async function(g){s("\u2192 GET",g.toString());try{let u=g.searchParams.get("uri");if(s("uri:",u??"(missing)"),!u)return s("\u2190 400 missing uri"),Response.json({error:"Missing uri query parameter"},{status:400});let a=t??(await r()).mcpServerUrl;s("mcpServerUrl:",a);let i,o;try{[{createMCPClient:i},{StreamableHTTPClientTransport:o}]=await Promise.all([import("@ai-sdk/mcp"),import("@modelcontextprotocol/sdk/client/streamableHttp.js")]),s("MCP deps loaded")}catch(n){return console.error("[waniwani:resource] MCP deps import failed:",n),Response.json({error:"MCP resource handler requires @ai-sdk/mcp and @modelcontextprotocol/sdk. Install them to enable resource serving."},{status:501})}s("creating MCP client for",a);let l=await i({transport:new o(new URL(a))});try{s("reading resource:",u);let n=await l.readResource({uri:u});s("resource contents count:",n.contents.length);let w=n.contents[0];if(!w)return s("\u2190 404 resource not found"),Response.json({error:"Resource not found"},{status:404});let m;return"text"in w&&typeof w.text=="string"?m=w.text:"blob"in w&&typeof w.blob=="string"&&(m=atob(w.blob)),m?(s("\u2190 200 HTML length:",m.length),new Response(m,{headers:{"Content-Type":"text/html","Cache-Control":"private, max-age=300"}})):(s("\u2190 404 resource has no content, keys:",Object.keys(w)),Response.json({error:"Resource has no content"},{status:404}))}finally{await l.close(),s("MCP client closed")}}catch(u){console.error("[waniwani:resource] handler error:",u);let a=u instanceof Error?u.message:"Unknown error occurred",i=u instanceof W?u.status:500;return s("\u2190 returning",i,"from caught error"),Response.json({error:a},{status:i})}}}function Ke(e){let{mcpServerUrl:t,resolveConfig:r,debug:c,source:s}=e,p=D("tool",c);return async function(u){p("\u2192 POST",u.url);try{let a=await u.json(),{name:i,arguments:o}=a,l=u.headers.get("x-session-id")?.trim();if(!i||typeof i!="string")return p("\u2190 400 missing tool name"),Response.json({error:"Missing tool name"},{status:400});p("tool:",i,"args:",JSON.stringify(o),"sessionId:",l||"(none)");let n=t??(await r()).mcpServerUrl;p("mcpServerUrl:",n);let w,m;try{[{Client:w},{StreamableHTTPClientTransport:m}]=await Promise.all([import("@modelcontextprotocol/sdk/client/index.js"),import("@modelcontextprotocol/sdk/client/streamableHttp.js")]),p("MCP deps loaded")}catch(M){return console.error("[waniwani:tool] MCP deps import failed:",M),Response.json({error:"MCP tool handler requires @modelcontextprotocol/sdk. Install it to enable tool calls."},{status:501})}p("creating MCP client for",n);let x=new m(new URL(n)),y=new w({name:"waniwani-tool-caller",version:"1.0.0"});await y.connect(x);try{p("calling tool:",i);let M={};l&&(M["waniwani/sessionId"]=l),s&&(M["waniwani/source"]=s);let T=await y.callTool({name:i,arguments:o??{},...Object.keys(M).length>0?{_meta:M}:{}});return p("tool result received"),Response.json({content:T.content,structuredContent:T.structuredContent,_meta:T._meta,isError:T.isError})}finally{await y.close(),p("MCP client closed")}}catch(a){console.error("[waniwani:tool] handler error:",a);let i=a instanceof Error?a.message:"Unknown error occurred",o=a instanceof W?a.status:500;return p("\u2190 returning",o,"from caught error"),Response.json({error:i},{status:o})}}}function Je(e){let{mcpServerUrl:t,resolveConfig:r,debug:c}=e,s=D("tools-list",c);return async function(){s("\u2192 GET tools/list");try{let g=t??(await r()).mcpServerUrl;s("mcpServerUrl:",g);let u,a;try{[{createMCPClient:u},{StreamableHTTPClientTransport:a}]=await Promise.all([import("@ai-sdk/mcp"),import("@modelcontextprotocol/sdk/client/streamableHttp.js")]),s("MCP deps loaded")}catch(o){return console.error("[waniwani:tools-list] MCP deps import failed:",o),Response.json({error:"MCP tools list handler requires @ai-sdk/mcp and @modelcontextprotocol/sdk. Install them to enable tool discovery."},{status:501})}s("creating MCP client for",g);let i=await u({transport:new a(new URL(g))});try{s("listing tools");let o=await i.listTools();s("tools count:",o.tools.length);let l={tools:o.tools.map(n=>({name:n.name,...n.title!==void 0&&{title:n.title},...n.description!==void 0&&{description:n.description},...n.inputSchema!==void 0&&{inputSchema:n.inputSchema},...n.outputSchema!==void 0&&{outputSchema:n.outputSchema},...n.annotations!==void 0&&{annotations:n.annotations},...n._meta!==void 0&&{_meta:n._meta}})),...o.nextCursor!==void 0&&{nextCursor:o.nextCursor}};return s("\u2190 200"),Response.json(l,{headers:{"Cache-Control":"private, max-age=60"}})}finally{await i.close(),s("MCP client closed")}}catch(g){console.error("[waniwani:tools-list] handler error:",g);let u=g instanceof Error?g.message:"Unknown error occurred",a=g instanceof W?g.status:500;return s("\u2190 returning",a,"from caught error"),Response.json({error:u},{status:a})}}}var It=300*1e3;function Ve(e,t){let r=null,c=null;return async function(){if(r&&Date.now()<r.expiresAt)return r.config;if(c)return c;c=(async()=>{if(!t)throw new W("WANIWANI_API_KEY is required for createChatHandler",401);let p=await fetch(`${e}/api/mcp/environments/config`,{method:"GET",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});if(!p.ok){let u=await p.text().catch(()=>"");throw new W(`Failed to resolve MCP environment config: ${p.status} ${u}`,p.status)}let g=await p.json();return r={config:g,expiresAt:Date.now()+It},g})();try{return await c}finally{c=null}}}var Et="https://app.waniwani.ai";function Ye(e={}){let{apiKey:t=process.env.WANIWANI_API_KEY,apiUrl:r=Et,source:c,systemPrompt:s,maxSteps:p=5,beforeRequest:g,mcpServerUrl:u,debug:a=!1,webSearch:i}=e,o=D("router",a),l=Fe(),n=Be(l),w=Ve(r,t),m=$e({apiKey:t,apiUrl:r,source:c,systemPrompt:s,maxSteps:p,beforeRequest:g,mcpServerUrl:u,resolveConfig:w,debug:a,webSearch:_e(i)}),x=ze({mcpServerUrl:u,resolveConfig:w,debug:a}),y=Je({mcpServerUrl:u,resolveConfig:w,debug:a}),M=Ke({mcpServerUrl:u,resolveConfig:w,debug:a,source:c}),T=process.env.WANIWANI_EVAL==="1";async function j(O){o("\u2192 GET",O.url);try{let R=new URL(O.url),C=R.pathname.replace(/\/$/,"").split("/").filter(Boolean).at(-1);if(o("pathname:",R.pathname,"subRoute:",C),T&&C==="scenarios"){o("dispatching to scenarios handler (proxy to app API)");try{let P=await(await fetch(`${r}/api/mcp/scenarios`,{headers:{...t?{Authorization:`Bearer ${t}`}:{}}})).json();return n(P.data??P,200)}catch{return n([],200)}}if(C==="resource"){o("dispatching to resource handler");let A=await x(R);return o("\u2190 resource handler returned",A.status),l(A)}if(C==="config")return o("dispatching to config handler"),n({debug:a,eval:T},200);if(C==="tools"){o("dispatching to tools-list handler");let A=await y();return o("\u2190 tools-list handler returned",A.status),l(A)}return o("\u2190 404 no matching sub-route for",C),n({error:"Not found"},404)}catch(R){console.error("[waniwani:router] GET handler error:",R);let U=R instanceof Error?R.message:"Unknown error occurred";return o("\u2190 500 from caught error"),n({error:U},500)}}async function q(O){o("\u2192 POST",O.url);try{let R=new URL(O.url),C=R.pathname.replace(/\/$/,"").split("/").filter(Boolean).at(-1);if(o("pathname:",R.pathname,"subRoute:",C),T&&C==="scenarios"){o("dispatching to save-scenario handler (proxy to app API)");try{let P=await O.json(),v=await fetch(`${r}/api/mcp/scenarios`,{method:"POST",headers:{"Content-Type":"application/json",...t?{Authorization:`Bearer ${t}`}:{}},body:JSON.stringify(P)}),I=await v.json();return v.ok?n({ok:!0,scenario:I.data},200):n({error:I.message??"Failed to save scenario"},v.status)}catch(P){let v=P instanceof Error?P.message:"Failed to save scenario";return n({error:v},400)}}if(C==="tool"){o("dispatching to tool handler");let P=await M(O);return o("\u2190 tool handler returned",P.status),l(P)}o("dispatching to chat handler");let A=await m(O);return l(A)}catch(R){console.error("[waniwani:router] POST handler error:",R);let U=R instanceof Error?R.message:"Unknown error occurred";return o("\u2190 500 from caught error"),n({error:U},500)}}async function N(O){o("\u2192 PATCH",O.url);try{let R=new URL(O.url),U=R.pathname.replace(/\/$/,"").split("/").filter(Boolean),C=U.at(-1),A=U.at(-2);if(o("pathname:",R.pathname,"subRoute:",A,"id:",C),T&&A==="scenarios"&&C){o("dispatching to update-scenario handler (proxy to app API)");try{let P=await O.json(),v=await fetch(`${r}/api/mcp/scenarios/${C}`,{method:"PATCH",headers:{"Content-Type":"application/json",...t?{Authorization:`Bearer ${t}`}:{}},body:JSON.stringify(P)}),I=await v.json();return v.ok?n({ok:!0,scenario:I.data},200):n({error:I.message??"Failed to update scenario"},v.status)}catch(P){let v=P instanceof Error?P.message:"Failed to update scenario";return n({error:v},400)}}return o("\u2190 404 no matching sub-route for PATCH",A),n({error:"Not found"},404)}catch(R){console.error("[waniwani:router] PATCH handler error:",R);let U=R instanceof Error?R.message:"Unknown error occurred";return o("\u2190 500 from caught error"),n({error:U},500)}}function _(){return l(new Response(null,{status:204}))}return{handleChat:m,handleResource:x,handleTool:M,routeGet:j,routePost:q,routePatch:N,handleOptions:_}}var Xe=!1;function qn(e,t){!Xe&&process.env.NODE_ENV!=="test"&&(console.warn("[waniwani-sdk] toNextJsHandler is deprecated; switch to toExpressJsHandler from @waniwani/sdk/express-js. It will be removed in a follow-up release."),Xe=!0);let{apiKey:r,apiUrl:c}=e._config,s=t?.debug??process.env.WANIWANI_DEBUG==="1",p=Ye({...t?.chat,apiKey:r,apiUrl:c,source:t?.source,debug:s});return{POST:p.routePost,GET:p.routeGet,PATCH:p.routePatch,OPTIONS:()=>p.handleOptions()}}export{be as DevModeProvider,st as InitializeNextJsInIframe,Ot as LoadingWidget,Re as WidgetProvider,fe as createResource,tt as createTool,se as detectPlatform,oe as getMockState,J as initializeMockOpenAI,Qe as isMCPApps,Ze as isOpenAI,ot as registerTools,qn as toNextJsHandler,Y as updateMockDisplayMode,F as updateMockGlobal,X as updateMockTheme,V as updateMockToolOutput,Se as useCallTool,Me as useDisplayMode,Te as useFlowAction,Pe as useIsChatGptApp,Ue as useLocale,Oe as useMaxHeight,Ae as useOpenExternal,We as useRequestDisplayMode,Ne as useSafeArea,Ie as useSendFollowUp,Ee as useTheme,ne as useToolOutput,He as useToolResponseMetadata,De as useUpdateModelContext,k as useWidgetClient,Le as useWidgetState};
2
69
  //# sourceMappingURL=index.js.map