@waniwani/sdk 0.18.1 → 0.19.1
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.
- package/dist/chat/embed.js +60 -60
- package/dist/chat/embed.js.map +1 -1
- package/dist/chat/index.d.ts +33 -4
- package/dist/chat/index.js +7 -7
- package/dist/chat/index.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/legacy/index.d.ts +22 -4
- package/dist/legacy/index.js +13 -13
- package/dist/legacy/index.js.map +1 -1
- package/dist/mcp/index.js +5 -5
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/react/skybridge.js +1 -1
- package/dist/mcp/react/skybridge.js.map +1 -1
- package/dist/mcp/react.js +5 -5
- package/dist/mcp/react.js.map +1 -1
- package/package.json +1 -1
package/dist/mcp/react.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{a as K,b as Te,c as Me}from"../chunk-DP6SAQTK.js";import{b as
|
|
2
|
+
import{a as K,b as Te,c as Me}from"../chunk-DP6SAQTK.js";import{b as F,c as Ie}from"../chunk-RZKVTH7F.js";import{Fragment as dt,jsx as P,jsxs as ut}from"react/jsx-runtime";function at(){let e=window.innerBaseUrl,t=window.__wwPassthroughOrigins??[],n=document.documentElement;new MutationObserver(u=>{u.forEach(p=>{if(p.type==="attributes"&&p.target===n){let a=p.attributeName;a&&a!=="suppresshydrationwarning"&&a!=="lang"&&a!=="class"&&a!=="style"&&n.removeAttribute(a)}})}).observe(n,{attributes:!0,attributeOldValue:!0});let r=history.replaceState.bind(history);history.replaceState=(u,p,a)=>{try{let f=new URL(String(a??""),window.location.href);r(null,p,f.pathname+f.search+f.hash)}catch{}};let i=history.pushState.bind(history);history.pushState=(u,p,a)=>{try{let f=new URL(String(a??""),window.location.href);i(null,p,f.pathname+f.search+f.hash)}catch{}};let d=new URL(e).origin,c=window.self!==window.top;if(window.addEventListener("click",u=>{let p=u?.target?.closest("a");if(!p||!p.href)return;let a=new URL(p.href,window.location.href);if(a.origin!==window.location.origin&&a.origin!==d)try{window.openai&&(window.openai?.openExternal({href:p.href}),u.preventDefault())}catch{console.warn("openExternal failed, likely not in OpenAI client")}},!0),c&&window.location.origin!==d){let u=window.fetch;window.fetch=((l,v)=>{let y=typeof l=="string"&&!/^[a-z][a-z0-9+.-]*:/i.test(l)&&!l.startsWith("//"),w;if(typeof l=="string"||l instanceof URL?w=new URL(l,window.location.href):w=new URL(l.url,window.location.href),w.origin===d)return typeof l=="string"||l instanceof URL?l=w.toString():l=new Request(w.toString(),l),u.call(window,l,{...v,mode:"cors"});if(t.indexOf(w.origin)!==-1)return u.call(window,l,v);if(y&&w.origin===window.location.origin){let T=new URL(e);return T.pathname=w.pathname,T.search=w.search,T.hash=w.hash,w=T,l=w.toString(),u.call(window,l,{...v,mode:"cors"})}return u.call(window,l,v)});let p=d.replace(/^http/,"ws"),a=window.WebSocket,f=((l,v)=>{let y=new URL(String(l),window.location.href);if(y.origin===window.location.origin||y.origin===window.location.origin.replace(/^http/,"ws")){let w=new URL(p);return w.pathname=y.pathname,w.search=y.search,w.hash=y.hash,new a(w.toString(),v)}return new a(l,v)});f.prototype=a.prototype,Object.assign(f,{CONNECTING:a.CONNECTING,OPEN:a.OPEN,CLOSING:a.CLOSING,CLOSED:a.CLOSED}),window.WebSocket=f}}var lt=`(${at.toString()})()`;function Ce({baseUrl:e,passthroughOrigins:t}){return ut(dt,{children:[P("base",{href:e}),P("script",{children:`window.innerBaseUrl = ${JSON.stringify(e)}`}),P("script",{children:`window.__wwPassthroughOrigins = ${JSON.stringify(t??[])}`}),P("script",{children:'window.__isChatGptApp = typeof window.openai !== "undefined";'}),P("script",{children:lt})]})}import{useCallback as S,useEffect as D,useRef as Z,useState as k}from"react";var Ee={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},L={...Ee};function U(e){typeof window>"u"||window.openai||(L={...Ee,toolOutput:e??null},window.openai={...L,requestDisplayMode:async({mode:t})=>(M("displayMode",t),{mode:t}),callTool:async(t,n)=>(console.log(`[DevMode] callTool: ${t}`,n),{result:JSON.stringify({mock:!0,tool:t,args:n})}),sendFollowUpMessage:async({prompt:t})=>{console.log(`[DevMode] sendFollowUpMessage: ${t}`)},openExternal:({href:t})=>{console.log(`[DevMode] openExternal: ${t}`),window.open(t,"_blank")},setWidgetState:async t=>{M("widgetState",t)}},window.dispatchEvent(new F({globals:L})))}function M(e,t){typeof window>"u"||!window.openai||(L[e]=t,window.openai[e]=t,window.dispatchEvent(new F({globals:{[e]:t}})))}function B(){return{...L}}function O(e){M("toolOutput",e)}function A(e){M("displayMode",e)}function W(e){M("theme",e)}import{Fragment as Q,jsx as s,jsxs as h}from"react/jsx-runtime";var z=150;function Re({className:e}){return h("svg",{className:e,viewBox:"0 0 24 24",fill:"none",role:"img","aria-label":"Dev Controls",children:[s("rect",{x:"4",y:"4",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5"}),s("rect",{x:"10",y:"10",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5",fill:"currentColor",fillOpacity:"0.15"})]})}function ct({className:e}){return s("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s("path",{d:"M18 6L6 18M6 6l12 12"})})}function pt({className:e}){return s("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:s("rect",{x:"2",y:"4",width:"12",height:"8",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"})})}function ft({className:e}){return h("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[s("rect",{x:"1.5",y:"3",width:"13",height:"10",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"}),s("rect",{x:"8.5",y:"7",width:"5",height:"4",rx:"0.75",fill:"currentColor"})]})}function gt({className:e}){return s("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:s("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 mt({className:e}){return h("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[s("circle",{cx:"8",cy:"8",r:"2.5",stroke:"currentColor",strokeWidth:"1.25"}),s("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 ht({className:e}){return s("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:s("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 wt({className:e}){return h("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[s("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"}),s("path",{d:"M12.5 2v3h-3M3.5 14v-3h3",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})]})}var yt=`
|
|
3
3
|
@keyframes devPanelSlideIn {
|
|
4
4
|
0% {
|
|
5
5
|
opacity: 0;
|
|
@@ -51,18 +51,18 @@ import{a as K,b as Te,c as Me}from"../chunk-DP6SAQTK.js";import{b as _,c as Ie}f
|
|
|
51
51
|
relative z-10 flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5
|
|
52
52
|
text-xs font-medium rounded-md transition-colors duration-150
|
|
53
53
|
${t===r.value?"text-white":"text-gray-400 hover:text-gray-300"}
|
|
54
|
-
`,children:[r.icon,s("span",{className:"capitalize",children:r.label})]},r.value))]})}function xt({defaultProps:e}){let[t,n]=k(()=>typeof window>"u"?!1:localStorage.getItem("dev-controls-open")==="true"),[o,r]=k(!1),[i,d]=k(t),[c,u]=k("inline"),[p,a]=k("dark"),[f,l]=k(!1),[v,y]=k(()=>JSON.stringify(e??{},null,2)),[w,T]=k(null),
|
|
54
|
+
`,children:[r.icon,s("span",{className:"capitalize",children:r.label})]},r.value))]})}function xt({defaultProps:e}){let[t,n]=k(()=>typeof window>"u"?!1:localStorage.getItem("dev-controls-open")==="true"),[o,r]=k(!1),[i,d]=k(t),[c,u]=k("inline"),[p,a]=k("dark"),[f,l]=k(!1),[v,y]=k(()=>JSON.stringify(e??{},null,2)),[w,T]=k(null),_=Z(null),Qe=Z(null),J=Z(null);D(()=>{let g=B();u(g.displayMode),a(g.theme)},[]),D(()=>{typeof window>"u"||(window.openai||(window.openai={}),window.openai.safeArea={insets:{top:0,bottom:f?z:0,left:0,right:0}},window.dispatchEvent(new F({globals:{safeArea:window.openai.safeArea}})))},[f]),D(()=>{localStorage.setItem("dev-controls-open",String(t))},[t]);let Se=S(()=>{d(!0),requestAnimationFrame(()=>{n(!0)})},[]),C=S(()=>{r(!0),n(!1),setTimeout(()=>{d(!1),r(!1)},150)},[]),X=S(()=>{t?C():Se()},[t,Se,C]);D(()=>{let g=b=>{(b.metaKey||b.ctrlKey)&&b.shiftKey&&b.key==="d"&&(b.preventDefault(),X()),b.key==="Escape"&&t&&C()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[t,X,C]),D(()=>{if(!t)return;let g=b=>{J.current&&!J.current.contains(b.target)&&C()};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[t,C]);let et=S(g=>{u(g),A(g)},[]),tt=S(g=>{a(g),W(g)},[]),V=S(g=>{try{let b=JSON.parse(g);T(null),O(b)}catch{T("Invalid JSON")}},[]),nt=S(g=>{y(g),_.current&&clearTimeout(_.current),_.current=setTimeout(()=>{V(g)},500)},[V]),ot=S(()=>{_.current&&clearTimeout(_.current),V(v)},[V,v]),rt=S(()=>{let g=JSON.stringify(e??{},null,2);y(g),T(null),O(e??{}),u("inline"),A("inline"),a("dark"),W("dark")},[e]),it=[{value:"inline",label:"inline",icon:s(pt,{className:"w-3.5 h-3.5"})},{value:"pip",label:"pip",icon:s(ft,{className:"w-3.5 h-3.5"})},{value:"fullscreen",label:"full",icon:s(gt,{className:"w-3.5 h-3.5"})}],st=[{value:"light",label:"light",icon:s(mt,{className:"w-3.5 h-3.5"})},{value:"dark",label:"dark",icon:s(ht,{className:"w-3.5 h-3.5"})}];return h(Q,{children:[s("style",{dangerouslySetInnerHTML:{__html:yt}}),h("div",{ref:J,className:"fixed bottom-4 right-4 z-[9999] font-['Inter',_system-ui,_sans-serif]",children:[h("button",{type:"button",onClick:X,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:`
|
|
55
55
|
0 4px 12px rgba(0, 0, 0, 0.4),
|
|
56
56
|
0 0 0 1px rgba(255, 255, 255, 0.05),
|
|
57
57
|
inset 0 1px 0 rgba(255, 255, 255, 0.04)
|
|
58
|
-
`},"aria-label":"Toggle Dev Controls","aria-expanded":t,children:[s(
|
|
58
|
+
`},"aria-label":"Toggle Dev Controls","aria-expanded":t,children:[s(Re,{className:`w-5 h-5 transition-all duration-200 ${t?"text-indigo-400 scale-110":"text-gray-300 group-hover:text-white"}`}),s("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%)"}})]}),i&&h("div",{ref:Qe,className:`absolute bottom-14 right-0 w-80 ${t&&!o?"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:`
|
|
59
59
|
0 25px 50px -12px rgba(0, 0, 0, 0.6),
|
|
60
60
|
0 0 0 1px rgba(255, 255, 255, 0.05),
|
|
61
61
|
inset 0 1px 0 rgba(255, 255, 255, 0.04)
|
|
62
|
-
`},children:[h("div",{className:"flex items-center justify-between px-4 py-3",style:{borderBottom:"1px solid rgba(255, 255, 255, 0.06)"},children:[h("div",{className:"flex items-center gap-2",children:[s(Ee,{className:"w-4 h-4 text-gray-400"}),s("span",{className:"text-sm font-medium text-white",children:"Dev Controls"})]}),h("div",{className:"flex items-center gap-2",children:[s("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"}),s("button",{type:"button",onClick:C,className:"p-1 rounded-md text-gray-500 hover:text-gray-300 hover:bg-white/5 transition-colors",children:s(ct,{className:"w-4 h-4"})})]})]}),h("div",{className:"p-4 space-y-5 overflow-y-auto",style:{maxHeight:"calc(100vh - 200px)"},children:[h("div",{children:[s("label",{htmlFor:"display-mode",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Display Mode"}),s(Ue,{options:it,value:c,onChange:et})]}),h("div",{children:[s("label",{htmlFor:"theme",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Theme"}),s(Ue,{options:st,value:p,onChange:tt})]}),h("div",{children:[s("label",{htmlFor:"safe-area",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Safe Area (Chat Input)"}),h("button",{type:"button",onClick:()=>l(!f),className:`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-xs font-medium transition-all duration-150 ${f?"text-emerald-400":"text-gray-400"}`,style:{background:f?"rgba(34, 197, 94, 0.1)":"rgba(255, 255, 255, 0.04)",border:f?"1px solid rgba(34, 197, 94, 0.3)":"1px solid rgba(255, 255, 255, 0.06)"},children:[s("span",{children:"Mock ChatGPT Input Bar"}),s("span",{className:`px-2 py-0.5 rounded text-[10px] font-semibold ${f?"bg-emerald-500/20 text-emerald-400":"bg-gray-500/20 text-gray-500"}`,children:f?"ON":"OFF"})]}),f&&h("p",{className:"text-[10px] text-gray-500 mt-1.5",children:["bottom: ",z,"px"]})]}),h("div",{children:[s("label",{htmlFor:"widget-props",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Widget Props"}),s("textarea",{value:v,onChange:g=>nt(g.target.value),onBlur:ot,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:w?"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:g=>{w||(g.target.style.borderColor="rgba(99, 102, 241, 0.5)")},onBlurCapture:g=>{w||(g.target.style.borderColor="rgba(255, 255, 255, 0.06)")},spellCheck:!1}),w&&h("p",{className:"text-red-400 text-[11px] mt-1.5 flex items-center gap-1",children:[s("svg",{"aria-hidden":"true","aria-label":"Error",className:"w-3 h-3",viewBox:"0 0 16 16",fill:"currentColor",children:s("path",{d:"M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM7 4.5h2v4H7v-4zm0 5h2v2H7v-2z"})}),w]})]}),h("button",{type:"button",onClick:rt,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:g=>{g.currentTarget.style.background="rgba(255, 255, 255, 0.08)",g.currentTarget.style.borderColor="rgba(255, 255, 255, 0.1)"},onMouseLeave:g=>{g.currentTarget.style.background="rgba(255, 255, 255, 0.04)",g.currentTarget.style.borderColor="rgba(255, 255, 255, 0.06)"},children:[s(wt,{className:"w-3.5 h-3.5"}),"Reset to Defaults"]})]})]})]}),f&&h("div",{className:"fixed bottom-0 left-0 right-0 z-[9998] flex items-center justify-center pointer-events-none",style:{height:`${z}px`,background:"linear-gradient(to top, #1a1a1a 0%, #1a1a1a 80%, transparent 100%)"},children:[h("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:[s("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:s("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),s("div",{className:"flex-1 text-gray-400 text-sm",children:"Ask me anything..."}),s("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:s("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:s("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"})})})]}),h("div",{className:"absolute bottom-1 text-[10px] text-gray-600 font-mono",children:["Mock SafeArea: bottom=",z,"px"]})]})]})}import{useCallback as kt,useContext as St,useLayoutEffect as Tt,useMemo as Mt,useRef as Oe}from"react";import{createContext as bt}from"react";var H=bt(null);import{Fragment as Ae,jsx as te}from"react/jsx-runtime";var It="waniwani:send-follow-up:advanced:",Ct=1e4;function We(e){return`${It}${e??"default"}`}function Rt(e){try{let t=globalThis.localStorage?.getItem(We(e));if(!t)return null;let n=JSON.parse(t);return typeof n?.at!="number"||typeof n?.byMountId!="string"?null:n}catch{return null}}function Et(e,t){try{globalThis.localStorage?.setItem(We(e),JSON.stringify({at:Date.now(),byMountId:t}))}catch{}}function ne(){return typeof window>"u"?!1:typeof window.openai=="object"}function Ut(){return ne()?window.openai:null}function Ot(){return Tt(()=>{let e=document.documentElement,t=document.body,n=e.getAttribute("style"),o=t.getAttribute("style"),r="margin:0!important;padding:0!important;border:0!important;background:transparent!important;background-color:transparent!important;height:0!important;min-height:0!important;max-height:0!important;overflow:hidden!important;";return e.setAttribute("style",r),t.setAttribute("style",r),()=>{n===null?e.removeAttribute("style"):e.setAttribute("style",n),o===null?t.removeAttribute("style"):t.setAttribute("style",o)}},[]),null}function oe(e){let t=St(H),n=Oe(e);n.current=e;let o=t?.getToolResponseMetadata?.()??null,r=Ut()?.toolResponseMetadata??null,i=o??r,d=i&&typeof i.viewUUID=="string"?i.viewUUID:void 0,c=Oe("");c.current===""&&(c.current=crypto.randomUUID());let u=kt((a,f)=>{ne()&&Et(d,c.current);try{Promise.resolve(n.current(a)).catch(l=>{console.error("[unstable_useSendFollowUpWithGhostGuard]",l)})}catch(l){console.error("[unstable_useSendFollowUpWithGhostGuard]",l)}},[d]),p=Mt(()=>{let a=c.current;return function({children:l}){if(!ne())return te(Ae,{children:l});let v=Rt(d);return v&&v.byMountId!==a&&Date.now()-v.at<Ct?te(Ot,{}):te(Ae,{children:l})}},[d]);return{sendFollowUp:u,Guard:p}}import{useCallback as Dt}from"react";import j,{useCallback as Fe,useContext as At,useEffect as Ne,useState as re,useSyncExternalStore as Wt}from"react";async function De(){let{detectPlatform:e}=await import("../platform-LKQFC3AJ.js");if(e()==="openai"){let{OpenAIWidgetClient:n}=await import("../openai-client-PUBKF5TI.js");return new n}else{let{MCPAppsWidgetClient:n}=await import("../mcp-apps-client-WEXKWHUI.js");return new n}}function ie({children:e,loading:t=null,onError:n}){let[o,r]=re(null),[i,d]=re(null),[c,u]=re(!0);return Ne(()=>{let p=!0,a=null;async function f(){try{let l=await De();await l.connect(),p?(a=l,r(l),u(!1)):l.close()}catch(l){p&&(console.error("error",l),d(l instanceof Error?l:new Error(String(l))),u(!1))}}return f(),()=>{p=!1,a?.close()}},[]),Ne(()=>{if(!o)return;let p=a=>{document.documentElement.classList.toggle("dark",a==="dark"),document.documentElement.style.colorScheme=a==="dark"?"dark":"auto"};return p(o.getTheme()),o.onThemeChange(p)},[o]),i&&n?j.createElement(j.Fragment,null,n(i)):c||!o?j.createElement(j.Fragment,null,t):j.createElement(H.Provider,{value:o},e)}function m(e){let t=At(H);if(!t)throw new Error("useWidgetClient must be used within a WidgetProvider");let n=Fe(i=>e==="toolOutput"?t.onToolResult(()=>i()):e==="theme"?t.onThemeChange(()=>i()):e==="displayMode"?t.onDisplayModeChange(()=>i()):e==="safeArea"?t.onSafeAreaChange(()=>i()):e==="maxHeight"?t.onMaxHeightChange(()=>i()):e==="toolResponseMetadata"?t.onToolResponseMetadataChange(()=>i()):e==="widgetState"?t.onWidgetStateChange(()=>i()):()=>{},[t,e]),o=Fe(()=>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]),r=Wt(n,o,o);return e?r:t}function se(){let e=m();return Dt((t,n)=>e.callTool(t,n),[e])}function ae(){return m("displayMode")}function G(){return m("toolOutput")}function le(){return{data:G()}}import{useSyncExternalStore as Ft}from"react";function de(){return Ft(()=>()=>{},()=>typeof window>"u"?!1:window.__isChatGptApp===!0,()=>!1)}function ue(){return m("locale")}function ce(){return m("maxHeight")}import{useCallback as Nt}from"react";function pe(){let e=m();return Nt(t=>e.openExternal(t),[e])}import{useCallback as _t}from"react";function fe(){let e=m();return _t(t=>e.requestDisplayMode(t),[e])}function ge(){return m("safeArea")}import{useCallback as Pt}from"react";function me(){let e=m();return Pt((t,n)=>{(async()=>{Ie(n?.modelContext)&&await Promise.resolve(e.updateModelContext(n.modelContext)),await Promise.resolve(e.sendFollowUp(t))})().catch(o=>{console.error("Failed to send follow-up message:",o)})},[e])}function he(){return m("theme")}function we(){return m("toolResponseMetadata")}import{useCallback as Lt}from"react";function ye(){let e=m();return Lt(async t=>{await Promise.resolve(e.updateModelContext(t))},[e])}import{useCallback as Bt,useEffect as Ht,useState as jt}from"react";function ve(e){let t=m("widgetState"),[n,o]=jt(()=>t??(typeof e=="function"?e():e??null));Ht(()=>{o(t)},[t]);let r=Bt(i=>{o(d=>{let c=typeof i=="function"?i(d):i;return K()==="openai"&&c!=null&&window.openai?.setWidgetState(c),c})},[]);return[n,r]}import{jsx as R,jsxs as _e}from"react/jsx-runtime";var Pe=()=>_e("div",{className:"flex flex-col items-center justify-center h-full min-h-[120px] gap-4",children:[_e("div",{className:"flex gap-2",children:[R("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-blue-400 to-cyan-400 animate-bounce [animation-delay:-0.3s]"}),R("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-cyan-400 to-teal-400 animate-bounce [animation-delay:-0.15s]"}),R("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-teal-400 to-emerald-400 animate-bounce"})]}),R("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..."}),R("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:R("div",{className:"w-16 h-16 rounded-full border-2 border-blue-400/20 animate-ping"})}),R("style",{children:`
|
|
62
|
+
`},children:[h("div",{className:"flex items-center justify-between px-4 py-3",style:{borderBottom:"1px solid rgba(255, 255, 255, 0.06)"},children:[h("div",{className:"flex items-center gap-2",children:[s(Re,{className:"w-4 h-4 text-gray-400"}),s("span",{className:"text-sm font-medium text-white",children:"Dev Controls"})]}),h("div",{className:"flex items-center gap-2",children:[s("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"}),s("button",{type:"button",onClick:C,className:"p-1 rounded-md text-gray-500 hover:text-gray-300 hover:bg-white/5 transition-colors",children:s(ct,{className:"w-4 h-4"})})]})]}),h("div",{className:"p-4 space-y-5 overflow-y-auto",style:{maxHeight:"calc(100vh - 200px)"},children:[h("div",{children:[s("label",{htmlFor:"display-mode",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Display Mode"}),s(Ue,{options:it,value:c,onChange:et})]}),h("div",{children:[s("label",{htmlFor:"theme",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Theme"}),s(Ue,{options:st,value:p,onChange:tt})]}),h("div",{children:[s("label",{htmlFor:"safe-area",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Safe Area (Chat Input)"}),h("button",{type:"button",onClick:()=>l(!f),className:`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-xs font-medium transition-all duration-150 ${f?"text-emerald-400":"text-gray-400"}`,style:{background:f?"rgba(34, 197, 94, 0.1)":"rgba(255, 255, 255, 0.04)",border:f?"1px solid rgba(34, 197, 94, 0.3)":"1px solid rgba(255, 255, 255, 0.06)"},children:[s("span",{children:"Mock ChatGPT Input Bar"}),s("span",{className:`px-2 py-0.5 rounded text-[10px] font-semibold ${f?"bg-emerald-500/20 text-emerald-400":"bg-gray-500/20 text-gray-500"}`,children:f?"ON":"OFF"})]}),f&&h("p",{className:"text-[10px] text-gray-500 mt-1.5",children:["bottom: ",z,"px"]})]}),h("div",{children:[s("label",{htmlFor:"widget-props",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Widget Props"}),s("textarea",{value:v,onChange:g=>nt(g.target.value),onBlur:ot,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:w?"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:g=>{w||(g.target.style.borderColor="rgba(99, 102, 241, 0.5)")},onBlurCapture:g=>{w||(g.target.style.borderColor="rgba(255, 255, 255, 0.06)")},spellCheck:!1}),w&&h("p",{className:"text-red-400 text-[11px] mt-1.5 flex items-center gap-1",children:[s("svg",{"aria-hidden":"true","aria-label":"Error",className:"w-3 h-3",viewBox:"0 0 16 16",fill:"currentColor",children:s("path",{d:"M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM7 4.5h2v4H7v-4zm0 5h2v2H7v-2z"})}),w]})]}),h("button",{type:"button",onClick:rt,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:g=>{g.currentTarget.style.background="rgba(255, 255, 255, 0.08)",g.currentTarget.style.borderColor="rgba(255, 255, 255, 0.1)"},onMouseLeave:g=>{g.currentTarget.style.background="rgba(255, 255, 255, 0.04)",g.currentTarget.style.borderColor="rgba(255, 255, 255, 0.06)"},children:[s(wt,{className:"w-3.5 h-3.5"}),"Reset to Defaults"]})]})]})]}),f&&h("div",{className:"fixed bottom-0 left-0 right-0 z-[9998] flex items-center justify-center pointer-events-none",style:{height:`${z}px`,background:"linear-gradient(to top, #1a1a1a 0%, #1a1a1a 80%, transparent 100%)"},children:[h("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:[s("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:s("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),s("div",{className:"flex-1 text-gray-400 text-sm",children:"Ask me anything..."}),s("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:s("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:s("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"})})})]}),h("div",{className:"absolute bottom-1 text-[10px] text-gray-600 font-mono",children:["Mock SafeArea: bottom=",z,"px"]})]})]})}import{useCallback as kt,useContext as St,useLayoutEffect as Tt,useMemo as Mt,useRef as Oe}from"react";import{createContext as bt}from"react";var G=bt(null);import{Fragment as Ae,jsx as te}from"react/jsx-runtime";var It="waniwani:send-follow-up:advanced:",Ct=1e4;function We(e){return`${It}${e??"default"}`}function Et(e){try{let t=globalThis.localStorage?.getItem(We(e));if(!t)return null;let n=JSON.parse(t);return typeof n?.at!="number"||typeof n?.byMountId!="string"?null:n}catch{return null}}function Rt(e,t){try{globalThis.localStorage?.setItem(We(e),JSON.stringify({at:Date.now(),byMountId:t}))}catch{}}function ne(){return typeof window>"u"?!1:typeof window.openai=="object"}function Ut(){return ne()?window.openai:null}function Ot(){return Tt(()=>{let e=document.documentElement,t=document.body,n=e.getAttribute("style"),o=t.getAttribute("style"),r="margin:0!important;padding:0!important;border:0!important;background:transparent!important;background-color:transparent!important;height:0!important;min-height:0!important;max-height:0!important;overflow:hidden!important;";return e.setAttribute("style",r),t.setAttribute("style",r),()=>{n===null?e.removeAttribute("style"):e.setAttribute("style",n),o===null?t.removeAttribute("style"):t.setAttribute("style",o)}},[]),null}function oe(e){let t=St(G),n=Oe(e);n.current=e;let o=t?.getToolResponseMetadata?.()??null,r=Ut()?.toolResponseMetadata??null,i=o??r,d=i&&typeof i.viewUUID=="string"?i.viewUUID:void 0,c=Oe("");c.current===""&&(c.current=crypto.randomUUID());let u=kt((a,f)=>{ne()&&Rt(d,c.current);try{Promise.resolve(n.current(a)).catch(l=>{console.error("[unstable_useSendFollowUpWithGhostGuard]",l)})}catch(l){console.error("[unstable_useSendFollowUpWithGhostGuard]",l)}},[d]),p=Mt(()=>{let a=c.current;return function({children:l}){if(!ne())return te(Ae,{children:l});let v=Et(d);return v&&v.byMountId!==a&&Date.now()-v.at<Ct?te(Ot,{}):te(Ae,{children:l})}},[d]);return{sendFollowUp:u,Guard:p}}import{useCallback as Dt}from"react";import H,{useCallback as Ne,useContext as At,useEffect as _e,useState as re,useSyncExternalStore as Wt}from"react";async function De(){let{detectPlatform:e}=await import("../platform-LKQFC3AJ.js");if(e()==="openai"){let{OpenAIWidgetClient:n}=await import("../openai-client-PUBKF5TI.js");return new n}else{let{MCPAppsWidgetClient:n}=await import("../mcp-apps-client-WEXKWHUI.js");return new n}}function ie({children:e,loading:t=null,onError:n}){let[o,r]=re(null),[i,d]=re(null),[c,u]=re(!0);return _e(()=>{let p=!0,a=null;async function f(){try{let l=await De();await l.connect(),p?(a=l,r(l),u(!1)):l.close()}catch(l){p&&(console.error("error",l),d(l instanceof Error?l:new Error(String(l))),u(!1))}}return f(),()=>{p=!1,a?.close()}},[]),_e(()=>{if(!o)return;let p=a=>{document.documentElement.classList.toggle("dark",a==="dark"),document.documentElement.style.colorScheme=a==="dark"?"dark":"auto"};return p(o.getTheme()),o.onThemeChange(p)},[o]),i&&n?H.createElement(H.Fragment,null,n(i)):c||!o?H.createElement(H.Fragment,null,t):H.createElement(G.Provider,{value:o},e)}function m(e){let t=At(G);if(!t)throw new Error("useWidgetClient must be used within a WidgetProvider");let n=Ne(i=>e==="toolOutput"?t.onToolResult(()=>i()):e==="theme"?t.onThemeChange(()=>i()):e==="displayMode"?t.onDisplayModeChange(()=>i()):e==="safeArea"?t.onSafeAreaChange(()=>i()):e==="maxHeight"?t.onMaxHeightChange(()=>i()):e==="toolResponseMetadata"?t.onToolResponseMetadataChange(()=>i()):e==="widgetState"?t.onWidgetStateChange(()=>i()):()=>{},[t,e]),o=Ne(()=>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]),r=Wt(n,o,o);return e?r:t}function se(){let e=m();return Dt((t,n)=>e.callTool(t,n),[e])}function ae(){return m("displayMode")}function j(){return m("toolOutput")}function le(){return{data:j()}}import{useSyncExternalStore as Nt}from"react";function de(){return Nt(()=>()=>{},()=>typeof window>"u"?!1:window.__isChatGptApp===!0,()=>!1)}function ue(){return m("locale")}function ce(){return m("maxHeight")}import{useCallback as _t}from"react";function pe(){let e=m();return _t(t=>e.openExternal(t),[e])}import{useCallback as Ft}from"react";function fe(){let e=m();return Ft(t=>e.requestDisplayMode(t),[e])}function ge(){return m("safeArea")}import{useCallback as Pt}from"react";function me(){let e=m();return Pt((t,n)=>{(async()=>{Ie(n?.modelContext)&&await Promise.resolve(e.updateModelContext(n.modelContext)),await Promise.resolve(e.sendFollowUp(t))})().catch(o=>{console.error("Failed to send follow-up message:",o)})},[e])}function he(){return m("theme")}function we(){return m("toolResponseMetadata")}import{useCallback as Lt}from"react";function ye(){let e=m();return Lt(async t=>{await Promise.resolve(e.updateModelContext(t))},[e])}import{useCallback as Bt,useEffect as Gt,useState as Ht}from"react";function ve(e){let t=m("widgetState"),[n,o]=Ht(()=>t??(typeof e=="function"?e():e??null));Gt(()=>{o(t)},[t]);let r=Bt(i=>{o(d=>{let c=typeof i=="function"?i(d):i;return K()==="openai"&&c!=null&&window.openai?.setWidgetState(c),c})},[]);return[n,r]}import{jsx as E,jsxs as Fe}from"react/jsx-runtime";var Pe=()=>Fe("div",{className:"flex flex-col items-center justify-center h-full min-h-[120px] gap-4",children:[Fe("div",{className:"flex gap-2",children:[E("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-blue-400 to-cyan-400 animate-bounce [animation-delay:-0.3s]"}),E("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-cyan-400 to-teal-400 animate-bounce [animation-delay:-0.15s]"}),E("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-teal-400 to-emerald-400 animate-bounce"})]}),E("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..."}),E("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:E("div",{className:"w-16 h-16 rounded-full border-2 border-blue-400/20 animate-ping"})}),E("style",{children:`
|
|
63
63
|
@keyframes shimmer {
|
|
64
64
|
0% { background-position: 200% 0; }
|
|
65
65
|
100% { background-position: -200% 0; }
|
|
66
66
|
}
|
|
67
|
-
`})]});import{useEffect as fn,useMemo as gn,useRef as mn,useState as hn}from"react";function F(e,t){for(let n of t){let o=e[n];if(typeof o=="string"&&o.length>0)return o}}var Gt=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],Vt=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],Kt=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],zt=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],qt=["waniwani/visitorId","visitorId"],Yt=["correlationId","openai/requestId"];var xe="waniwani/widget";function Le(e){return e?F(e,Gt):void 0}function Be(e){return e?F(e,Vt):void 0}function He(e){return e?F(e,Kt):void 0}function je(e){return e?F(e,zt):void 0}function Ge(e){return e?F(e,qt):void 0}function Ve(e){return e?F(e,Yt):void 0}var $t=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],Jt=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function Ke(e,t){if(e){let o=e["waniwani/source"];if(typeof o=="string"&&o.length>0)return o;for(let{key:r,source:i}of $t){let d=e[r];if(typeof d=="string"&&d.length>0)return i}}let n=t?.name;if(typeof n=="string"&&n.length>0){let o=n.toLowerCase();for(let{needle:r,source:i}of Jt)if(o.includes(r))return i}}var Xt="@waniwani/sdk";function ze(e,t={}){let n=t.now??(()=>new Date),o=t.generateId??Zt,r=tn(e),i=q(e.meta),d=q(e.metadata),c=nn(e,i),u=x(e.eventId)??o(),p=on(e.timestamp,n),a=x(e.source)??Ke(i)??t.source??Xt,f=be(e)?{...e}:void 0,l={...d};return Object.keys(i).length>0&&(l.meta=i),f&&(l.rawLegacy=f),{id:u,type:"mcp.event",name:r,source:a,timestamp:p,correlation:c,properties:Qt(e,r),metadata:l,rawLegacy:f}}function Zt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function Qt(e,t){if(!be(e))return q(e.properties);let n=en(e,t),o=q(e.properties);return{...n,...o}}function en(e,t){switch(t){case"tool.called":{let n={};return x(e.toolName)&&(n.name=e.toolName),x(e.toolType)&&(n.type=e.toolType),n}case"link.clicked":{let n={};return x(e.linkUrl)&&(n.url=e.linkUrl),n}default:return{}}}function tn(e){return be(e)?e.eventType:e.event}function nn(e,t){let n=x(e.requestId)??Be(t),o=x(e.sessionId)??Le(t),r=x(e.traceId)??He(t),i=x(e.externalUserId)??je(t),d=x(e.visitorId)??Ge(t),c=x(e.correlationId)??Ve(t)??n,u={};return o&&(u.sessionId=o),r&&(u.traceId=r),n&&(u.requestId=n),c&&(u.correlationId=c),i&&(u.externalUserId=i),d&&(u.visitorId=d),u}function on(e,t){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){let n=new Date(e);if(!Number.isNaN(n.getTime()))return n.toISOString()}return t().toISOString()}function q(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function x(e){if(typeof e=="string"&&e.trim().length!==0)return e}function be(e){return"eventType"in e}function qe(e){return{priceShown:({amount:t,currency:n,itemId:o,label:r,...i})=>e({event:"price_shown",properties:{amount:t,currency:n,itemId:o,label:r},...i}),pricesCompared:({options:t,...n})=>e({event:"prices_compared",properties:{options:t},...n}),optionSelected:({id:t,amount:n,currency:o,...r})=>e({event:"option_selected",properties:{id:t,amount:n,currency:o},...r}),leadQualified:t=>{let{externalId:n,email:o,name:r,...i}=t??{};return e({event:"lead_qualified",properties:{externalId:n,email:o,name:r},...i})},converted:({amount:t,currency:n,occurredAt:o,...r})=>e({event:"converted",properties:{amount:t,currency:n,occurredAt:o},...r})}}var rn="/api/mcp/events/v2/batch";var Ye="@waniwani/sdk";var sn=new Set([401,403]),an=new Set([408,425,429,500,502,503,504]);function $e(e){return new ke(e)}var ke=class{endpointUrl;flushIntervalMs;maxBatchSize;maxBufferSize;maxRetries;retryBaseDelayMs;retryMaxDelayMs;shutdownTimeoutMs;sdkVersion;fetchFn;logger;now;sleep;apiKey;buffer=[];flushTimer;flushScheduled=!1;flushScheduledTimer;flushInFlight;inFlightCount=0;isStopped=!1;isShuttingDown=!1;constructor(t){this.endpointUrl=un(t.apiUrl,t.endpointPath??rn),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??fetch,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(n=>new Promise(o=>setTimeout(o,n))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs)),this.registerBrowserTeardown()}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[Waniwani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let n=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,n),this.logger.warn("[Waniwani] Tracking buffer overflow, dropped %d oldest event(s)",n)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let n=t?.timeoutMs??this.shutdownTimeoutMs,o=this.flush();if(!Number.isFinite(n)||n<=0)return await o,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let r=Symbol("shutdown-timeout");return await Promise.race([o.then(()=>"flushed"),this.sleep(n).then(()=>r)])===r?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}registerBrowserTeardown(){if(typeof document>"u"||typeof window>"u")return;let t=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush()};document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",()=>this.keepaliveFlush())}keepaliveFlush(){if(this.isStopped||this.buffer.length===0)return;let t=this.buffer.splice(0,this.buffer.length);this.sendKeepaliveChunk(t)}sendKeepaliveChunk(t){let n=JSON.stringify(this.makeBatchRequest(t));if(n.length>6e4&&t.length>1){let o=Math.ceil(t.length/2);this.sendKeepaliveChunk(t.slice(0,o)),this.sendKeepaliveChunk(t.slice(o));return}try{this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:n,keepalive:!0}).catch(()=>{})}catch{}}requestHeaders(){let t={"Content-Type":"application/json","X-WaniWani-SDK":Ye};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let n=0,o=t;for(;o.length>0&&!this.isStopped;){this.inFlightCount=o.length;let r=await this.sendBatchOnce(o);switch(this.inFlightCount=0,r.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(r.status,o.length);return;case"permanent":this.logger.error("[Waniwani] Dropping %d event(s) after permanent failure: %s",o.length,r.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d event(s) after retry exhaustion: %s",o.length,r.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(r.permanent.length>0&&this.logger.error("[Waniwani] Dropping %d event(s) rejected as permanent",r.permanent.length),r.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d retryable event(s) after retry exhaustion",r.retryable.length);return}o=r.retryable,await this.sleep(this.backoffDelayMs(n)),n+=1;continue}}}async sendBatchOnce(t){let n;try{n=await this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:cn(i)}}if(sn.has(n.status))return{kind:"auth",status:n.status};if(an.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let o=await dn(n);if(!o?.rejected||o.rejected.length===0)return{kind:"success"};let r=this.classifyRejectedEvents(t,o.rejected);return r.retryable.length===0&&r.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:r.retryable,permanent:r.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:Ye,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let o=new Map(t.map(d=>[d.id,d])),r=[],i=[];for(let d of n){let c=o.get(d.eventId);if(c){if(ln(d)){r.push(c);continue}i.push(c)}}return{retryable:r,permanent:i}}backoffDelayMs(t){let n=this.retryBaseDelayMs*2**t;return Math.min(n,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,n){this.isStopped=!0;let o=this.buffer.length;this.buffer.splice(0,o),this.logger.error("[Waniwani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,n+o)}};function ln(e){if(e.retryable===!0)return!0;let t=e.code.toLowerCase();return t.includes("timeout")||t.includes("temporary")||t.includes("unavailable")||t.includes("rate_limit")||t.includes("transient")||t.includes("server")}async function dn(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function un(e,t){let n=e.endsWith("/")?e:`${e}/`,o=t.startsWith("/")?t.slice(1):t;return`${n}${o}`}function cn(e){return e instanceof Error?e.message:String(e)}function Je(e){let{apiUrl:t,endpointPath:n}=pn(e.endpoint),o=$e({apiUrl:t,apiKey:e.token,endpointPath:n,flushIntervalMs:e.flushIntervalMs}),r,i=c=>typeof c=="function"?c():c,d=async c=>{let u=e.identity?.()??{},p=i(e.channelId),a=p===void 0?c.properties:{channelId:p,...c.properties},f=ze({sessionId:u.sessionId,visitorId:u.visitorId,externalUserId:u.externalUserId??r,traceId:u.traceId,...c,properties:a,metadata:{...e.metadata,...c.metadata}},{source:i(e.source)});return o.enqueue(f),{eventId:f.id}};return{track:Object.assign(d,qe(d)),identify(c,u){return r=c,d({event:"user.identified",externalUserId:c,properties:u})},flush:()=>o.flush(),shutdown:c=>o.shutdown(c)}}function pn(e){let t=new URL(e);return{apiUrl:t.origin,endpointPath:`${t.pathname}${t.search}`}}var E=async()=>({eventId:""});function wn(){return Object.assign(E,{priceShown:E,pricesCompared:E,optionSelected:E,leadQualified:E,converted:E})}var Xe={sessionId:void 0,track:wn(),identify:E,flush:async()=>{}},Y=null,$=0;function I(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function yn(e){if(!e)return null;let t=e._meta,n=e[xe]??t?.[xe],o=I(n?.endpoint);return o?{endpoint:o,token:I(n?.token),sessionId:I(n?.sessionId),source:I(n?.source)}:null}function vn(e,t){return e?.endpoint===t?.endpoint&&e?.token===t?.token&&e?.sessionId===t?.sessionId&&e?.source===t?.source}function xn(e,t){let n=e.sessionId??crypto.randomUUID(),o=crypto.randomUUID(),r=Je({endpoint:e.endpoint,token:e.token,source:e.source,identity:()=>({sessionId:n,traceId:o}),metadata:t});return r.track({event:"widget_render"}),{config:e,widget:{sessionId:n,track:r.track,identify:(i,d)=>r.identify(i,d),flush:()=>r.flush()},cleanup:()=>{r.shutdown()}}}function Ze(e={}){let t=I(e.endpoint),n=I(e.token),o=I(e.sessionId),r=I(e.source),i=t?null:yn(e.toolResponseMetadata??null),d=i?.endpoint,c=i?.token,u=i?.sessionId,p=i?.source,a=gn(()=>{let y=r??p;return y?t?{endpoint:t,token:n,sessionId:o,source:y}:d?{endpoint:d,token:n??c,sessionId:o??u,source:y}:null:null},[t,n,o,r,d,c,u,p]),[f,l]=hn(Xe),v=mn(e.metadata);return v.current=e.metadata,fn(()=>{if(typeof window>"u")return;if(!a){l(Xe);return}let y=Y;return(!y||!vn(y.config,a))&&(y?.cleanup(),y=xn(a,v.current),Y=y),l(y.widget),$++,()=>{$=Math.max($-1,0),$===0&&(Y?.cleanup(),Y=null)}},[a]),f}export{ee as DevModeProvider,Ce as InitializeNextJsInIframe,Pe as LoadingWidget,ie as WidgetProvider,K as detectPlatform,B as getMockState,U as initializeMockOpenAI,Me as isMCPApps,Te as isOpenAI,oe as unstable_useSendFollowUpWithGhostGuard,A as updateMockDisplayMode,M as updateMockGlobal,W as updateMockTheme,O as updateMockToolOutput,se as useCallTool,ae as useDisplayMode,le as useFlowAction,de as useIsChatGptApp,ue as useLocale,ce as useMaxHeight,pe as useOpenExternal,fe as useRequestDisplayMode,ge as useSafeArea,me as useSendFollowUp,he as useTheme,G as useToolOutput,we as useToolResponseMetadata,ye as useUpdateModelContext,Ze as useWaniwani,m as useWidgetClient,ve as useWidgetState};
|
|
67
|
+
`})]});import{useEffect as fn,useMemo as gn,useRef as mn,useState as hn}from"react";function N(e,t){for(let n of t){let o=e[n];if(typeof o=="string"&&o.length>0)return o}}var jt=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],Vt=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],Kt=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],zt=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],qt=["waniwani/visitorId","visitorId"],Yt=["correlationId","openai/requestId"];var xe="waniwani/widget";function Le(e){return e?N(e,jt):void 0}function Be(e){return e?N(e,Vt):void 0}function Ge(e){return e?N(e,Kt):void 0}function He(e){return e?N(e,zt):void 0}function je(e){return e?N(e,qt):void 0}function Ve(e){return e?N(e,Yt):void 0}var $t=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],Jt=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function Ke(e,t){if(e){let o=e["waniwani/source"];if(typeof o=="string"&&o.length>0)return o;for(let{key:r,source:i}of $t){let d=e[r];if(typeof d=="string"&&d.length>0)return i}}let n=t?.name;if(typeof n=="string"&&n.length>0){let o=n.toLowerCase();for(let{needle:r,source:i}of Jt)if(o.includes(r))return i}}var Xt="@waniwani/sdk";function ze(e,t={}){let n=t.now??(()=>new Date),o=t.generateId??Zt,r=tn(e),i=q(e.meta),d=q(e.metadata),c=nn(e,i),u=x(e.eventId)??o(),p=on(e.timestamp,n),a=x(e.source)??Ke(i)??t.source??Xt,f=be(e)?{...e}:void 0,l={...d};return Object.keys(i).length>0&&(l.meta=i),f&&(l.rawLegacy=f),{id:u,type:"mcp.event",name:r,source:a,timestamp:p,correlation:c,properties:Qt(e,r),metadata:l,rawLegacy:f}}function Zt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function Qt(e,t){if(!be(e))return q(e.properties);let n=en(e,t),o=q(e.properties);return{...n,...o}}function en(e,t){switch(t){case"tool.called":{let n={};return x(e.toolName)&&(n.name=e.toolName),x(e.toolType)&&(n.type=e.toolType),n}case"link.clicked":{let n={};return x(e.linkUrl)&&(n.url=e.linkUrl),n}default:return{}}}function tn(e){return be(e)?e.eventType:e.event}function nn(e,t){let n=x(e.requestId)??Be(t),o=x(e.sessionId)??Le(t),r=x(e.traceId)??Ge(t),i=x(e.externalUserId)??He(t),d=x(e.visitorId)??je(t),c=x(e.correlationId)??Ve(t)??n,u={};return o&&(u.sessionId=o),r&&(u.traceId=r),n&&(u.requestId=n),c&&(u.correlationId=c),i&&(u.externalUserId=i),d&&(u.visitorId=d),u}function on(e,t){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){let n=new Date(e);if(!Number.isNaN(n.getTime()))return n.toISOString()}return t().toISOString()}function q(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function x(e){if(typeof e=="string"&&e.trim().length!==0)return e}function be(e){return"eventType"in e}function qe(e){return{priceShown:({amount:t,currency:n,itemId:o,label:r,...i})=>e({event:"price_shown",properties:{amount:t,currency:n,itemId:o,label:r},...i}),pricesCompared:({options:t,...n})=>e({event:"prices_compared",properties:{options:t},...n}),optionSelected:({id:t,amount:n,currency:o,...r})=>e({event:"option_selected",properties:{id:t,amount:n,currency:o},...r}),leadQualified:t=>{let{externalId:n,email:o,name:r,...i}=t??{};return e({event:"lead_qualified",properties:{externalId:n,email:o,name:r},...i})},converted:({amount:t,currency:n,occurredAt:o,...r})=>e({event:"converted",properties:{amount:t,currency:n,occurredAt:o},...r})}}var rn="/api/mcp/events/v2/batch";var Ye="@waniwani/sdk";var sn=new Set([401,403]),an=new Set([408,425,429,500,502,503,504]);function $e(e){return new ke(e)}var ke=class{endpointUrl;flushIntervalMs;maxBatchSize;maxBufferSize;maxRetries;retryBaseDelayMs;retryMaxDelayMs;shutdownTimeoutMs;sdkVersion;fetchFn;logger;now;sleep;apiKey;buffer=[];flushTimer;flushScheduled=!1;flushScheduledTimer;flushInFlight;inFlightCount=0;isStopped=!1;isShuttingDown=!1;constructor(t){this.endpointUrl=un(t.apiUrl,t.endpointPath??rn),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??fetch,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(n=>new Promise(o=>setTimeout(o,n))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs)),this.registerBrowserTeardown()}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[Waniwani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let n=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,n),this.logger.warn("[Waniwani] Tracking buffer overflow, dropped %d oldest event(s)",n)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let n=t?.timeoutMs??this.shutdownTimeoutMs,o=this.flush();if(!Number.isFinite(n)||n<=0)return await o,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let r=Symbol("shutdown-timeout");return await Promise.race([o.then(()=>"flushed"),this.sleep(n).then(()=>r)])===r?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}registerBrowserTeardown(){if(typeof document>"u"||typeof window>"u")return;let t=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush()};document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",()=>this.keepaliveFlush())}keepaliveFlush(){if(this.isStopped||this.buffer.length===0)return;let t=this.buffer.splice(0,this.buffer.length);this.sendKeepaliveChunk(t)}sendKeepaliveChunk(t){let n=JSON.stringify(this.makeBatchRequest(t));if(n.length>6e4&&t.length>1){let o=Math.ceil(t.length/2);this.sendKeepaliveChunk(t.slice(0,o)),this.sendKeepaliveChunk(t.slice(o));return}try{this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:n,keepalive:!0}).catch(()=>{})}catch{}}requestHeaders(){let t={"Content-Type":"application/json","X-WaniWani-SDK":Ye};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let n=0,o=t;for(;o.length>0&&!this.isStopped;){this.inFlightCount=o.length;let r=await this.sendBatchOnce(o);switch(this.inFlightCount=0,r.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(r.status,o.length);return;case"permanent":this.logger.error("[Waniwani] Dropping %d event(s) after permanent failure: %s",o.length,r.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d event(s) after retry exhaustion: %s",o.length,r.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(r.permanent.length>0&&this.logger.error("[Waniwani] Dropping %d event(s) rejected as permanent",r.permanent.length),r.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d retryable event(s) after retry exhaustion",r.retryable.length);return}o=r.retryable,await this.sleep(this.backoffDelayMs(n)),n+=1;continue}}}async sendBatchOnce(t){let n;try{n=await this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:cn(i)}}if(sn.has(n.status))return{kind:"auth",status:n.status};if(an.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let o=await dn(n);if(!o?.rejected||o.rejected.length===0)return{kind:"success"};let r=this.classifyRejectedEvents(t,o.rejected);return r.retryable.length===0&&r.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:r.retryable,permanent:r.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:Ye,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let o=new Map(t.map(d=>[d.id,d])),r=[],i=[];for(let d of n){let c=o.get(d.eventId);if(c){if(ln(d)){r.push(c);continue}i.push(c)}}return{retryable:r,permanent:i}}backoffDelayMs(t){let n=this.retryBaseDelayMs*2**t;return Math.min(n,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,n){this.isStopped=!0;let o=this.buffer.length;this.buffer.splice(0,o),this.logger.error("[Waniwani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,n+o)}};function ln(e){if(e.retryable===!0)return!0;let t=e.code.toLowerCase();return t.includes("timeout")||t.includes("temporary")||t.includes("unavailable")||t.includes("rate_limit")||t.includes("transient")||t.includes("server")}async function dn(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function un(e,t){let n=e.endsWith("/")?e:`${e}/`,o=t.startsWith("/")?t.slice(1):t;return`${n}${o}`}function cn(e){return e instanceof Error?e.message:String(e)}function Je(e){let{apiUrl:t,endpointPath:n}=pn(e.endpoint),o=$e({apiUrl:t,apiKey:e.token,endpointPath:n,flushIntervalMs:e.flushIntervalMs}),r,i=c=>typeof c=="function"?c():c,d=async c=>{let u=e.identity?.()??{},p=i(e.channelId),a=p===void 0?c.properties:{channelId:p,...c.properties},f=ze({sessionId:u.sessionId,visitorId:u.visitorId,externalUserId:u.externalUserId??r,traceId:u.traceId,...c,properties:a,metadata:{...e.metadata,...c.metadata}},{source:i(e.source)});return o.enqueue(f),{eventId:f.id}};return{track:Object.assign(d,qe(d)),identify(c,u){return r=c,d({event:"user.identified",externalUserId:c,properties:u})},flush:()=>o.flush(),shutdown:c=>o.shutdown(c)}}function pn(e){let t=new URL(e);return{apiUrl:t.origin,endpointPath:`${t.pathname}${t.search}`}}var R=async()=>({eventId:""});function wn(){return Object.assign(R,{priceShown:R,pricesCompared:R,optionSelected:R,leadQualified:R,converted:R})}var Xe={sessionId:void 0,track:wn(),identify:R,flush:async()=>{}},Y=null,$=0;function I(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function yn(e){if(!e)return null;let t=e._meta,n=e[xe]??t?.[xe],o=I(n?.endpoint);return o?{endpoint:o,token:I(n?.token),sessionId:I(n?.sessionId),source:I(n?.source)}:null}function vn(e,t){return e?.endpoint===t?.endpoint&&e?.token===t?.token&&e?.sessionId===t?.sessionId&&e?.source===t?.source}function xn(e,t){let n=e.sessionId??crypto.randomUUID(),o=crypto.randomUUID(),r=Je({endpoint:e.endpoint,token:e.token,source:e.source,identity:()=>({sessionId:n,traceId:o}),metadata:t});return r.track({event:"widget_render"}),{config:e,widget:{sessionId:n,track:r.track,identify:(i,d)=>r.identify(i,d),flush:()=>r.flush()},cleanup:()=>{r.shutdown()}}}function Ze(e={}){let t=I(e.endpoint),n=I(e.token),o=I(e.sessionId),r=I(e.source),i=t?null:yn(e.toolResponseMetadata??null),d=i?.endpoint,c=i?.token,u=i?.sessionId,p=i?.source,a=gn(()=>{let y=r??p;return y?t?{endpoint:t,token:n,sessionId:o,source:y}:d?{endpoint:d,token:n??c,sessionId:o??u,source:y}:null:null},[t,n,o,r,d,c,u,p]),[f,l]=hn(Xe),v=mn(e.metadata);return v.current=e.metadata,fn(()=>{if(typeof window>"u")return;if(!a){l(Xe);return}let y=Y;return(!y||!vn(y.config,a))&&(y?.cleanup(),y=xn(a,v.current),Y=y),l(y.widget),$++,()=>{$=Math.max($-1,0),$===0&&(Y?.cleanup(),Y=null)}},[a]),f}export{ee as DevModeProvider,Ce as InitializeNextJsInIframe,Pe as LoadingWidget,ie as WidgetProvider,K as detectPlatform,B as getMockState,U as initializeMockOpenAI,Me as isMCPApps,Te as isOpenAI,oe as unstable_useSendFollowUpWithGhostGuard,A as updateMockDisplayMode,M as updateMockGlobal,W as updateMockTheme,O as updateMockToolOutput,se as useCallTool,ae as useDisplayMode,le as useFlowAction,de as useIsChatGptApp,ue as useLocale,ce as useMaxHeight,pe as useOpenExternal,fe as useRequestDisplayMode,ge as useSafeArea,me as useSendFollowUp,he as useTheme,j as useToolOutput,we as useToolResponseMetadata,ye as useUpdateModelContext,Ze as useWaniwani,m as useWidgetClient,ve as useWidgetState};
|
|
68
68
|
//# sourceMappingURL=react.js.map
|