@waniwani/sdk 0.16.0 → 0.17.0
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 +54 -54
- package/dist/chat/embed.js.map +1 -1
- package/dist/chat/index.d.ts +46 -0
- package/dist/chat/index.js +7 -7
- package/dist/chat/index.js.map +1 -1
- package/dist/chat/styles.css +1 -1
- package/dist/legacy/index.d.ts +44 -0
- package/dist/legacy/index.js +12 -12
- package/dist/legacy/index.js.map +1 -1
- package/dist/legacy/mcp/react.js.map +1 -1
- package/dist/mcp/react/skybridge.d.ts +355 -0
- package/dist/mcp/react/skybridge.js +3 -0
- package/dist/mcp/react/skybridge.js.map +1 -0
- package/dist/mcp/react.d.ts +24 -10
- package/dist/mcp/react.js +7 -7
- package/dist/mcp/react.js.map +1 -1
- package/package.json +11 -2
- package/dist/chunk-GYLVCP7M.js +0 -3
- package/dist/chunk-GYLVCP7M.js.map +0 -1
- package/dist/widget-client-4MBLDRHD.js +0 -3
- package/dist/widget-client-4MBLDRHD.js.map +0 -1
package/dist/mcp/react.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{a as K,b as
|
|
2
|
+
import{a as K,b as Te,c as Me}from"../chunk-DP6SAQTK.js";import{b as _,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 Re={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={...Re};function U(e){typeof window>"u"||window.openai||(L={...Re,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 _({globals:L})))}function M(e,t){typeof window>"u"||!window.openai||(L[e]=t,window.openai[e]=t,window.dispatchEvent(new _({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 q=150;function Ee({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;
|
|
@@ -47,22 +47,22 @@ import{a as K,b as Me,c as Ce}from"../chunk-DP6SAQTK.js";import{b as L,c as Ee}f
|
|
|
47
47
|
.dev-json-editor::-webkit-scrollbar-thumb:hover {
|
|
48
48
|
background: rgba(255, 255, 255, 0.15);
|
|
49
49
|
}
|
|
50
|
-
`;function ee({defaultProps:e,widgetPaths:t,children:n}){let[r
|
|
50
|
+
`;function ee({defaultProps:e,widgetPaths:t,children:n}){let[o,r]=k(!1),[i,d]=k(!1);return D(()=>{if(new URLSearchParams(window.location.search).get("platform")==="mcp-apps"){r(!0);return}if(t&&t.length>0){let u=window.location.pathname,p=t.some(a=>u===a||u.startsWith(`${a}/`));d(p),p&&U(e)}else U(e),d(!0);r(!0)},[e,t]),o?i?h(Q,{children:[s(vt,{children:n}),s(xt,{defaultProps:e})]}):s(Q,{children:n}):null}function vt({children:e}){return s("div",{className:"min-h-screen bg-[#212121] flex items-center justify-center p-8",children:s("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 Ue({options:e,value:t,onChange:n}){let o=e.findIndex(r=>r.value===t);return h("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:[s("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(${o*100}% + ${o*2}px))`,background:"rgba(255, 255, 255, 0.1)"}}),e.map(r=>h("button",{type:"button",onClick:()=>n(r.value),className:`
|
|
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
|
-
${t===
|
|
54
|
-
`,children:[
|
|
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),N=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?q:0,left:0,right:0}},window.dispatchEvent(new _({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),N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{V(g)},500)},[V]),ot=S(()=>{N.current&&clearTimeout(N.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(Ee,{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(We,{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(mt,{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(Ae,{options:dt,value:l,onChange:ot})]}),h("div",{children:[s("label",{htmlFor:"theme",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Theme"}),s(Ae,{options:ut,value:f,onChange:it})]}),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:()=>c(!u),className:`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-xs font-medium transition-all duration-150 ${u?"text-emerald-400":"text-gray-400"}`,style:{background:u?"rgba(34, 197, 94, 0.1)":"rgba(255, 255, 255, 0.04)",border:u?"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 ${u?"bg-emerald-500/20 text-emerald-400":"bg-gray-500/20 text-gray-500"}`,children:u?"ON":"OFF"})]}),u&&h("p",{className:"text-[10px] text-gray-500 mt-1.5",children:["bottom: ",q,"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:y,onChange:g=>st(g.target.value),onBlur:at,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:lt,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(bt,{className:"w-3.5 h-3.5"}),"Reset to Defaults"]})]})]})]}),u&&h("div",{className:"fixed bottom-0 left-0 right-0 z-[9998] flex items-center justify-center pointer-events-none",style:{height:`${q}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=",q,"px"]})]})]})}import{useCallback as Mt,useContext as Ct,useLayoutEffect as Et,useMemo as Rt,useRef as De}from"react";import{createContext as It}from"react";var E=It(null);import{Fragment as Ne,jsx as te}from"react/jsx-runtime";var Ut="waniwani:send-follow-up:advanced:",Ot=1e4;function Fe(e){return`${Ut}${e??"default"}`}function Wt(e){try{let t=globalThis.localStorage?.getItem(Fe(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 At(e,t){try{globalThis.localStorage?.setItem(Fe(e),JSON.stringify({at:Date.now(),byMountId:t}))}catch{}}function ne(){return typeof window>"u"?!1:typeof window.openai=="object"}function Dt(){return ne()?window.openai:null}function Nt(){return Et(()=>{let e=document.documentElement,t=document.body,n=e.getAttribute("style"),r=t.getAttribute("style"),o="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",o),t.setAttribute("style",o),()=>{n===null?e.removeAttribute("style"):e.setAttribute("style",n),r===null?t.removeAttribute("style"):t.setAttribute("style",r)}},[]),null}function re(e){let t=Ct(E),n=De(e);n.current=e;let r=t?.getToolResponseMetadata?.()??null,o=Dt()?.toolResponseMetadata??null,i=r??o,a=i&&typeof i.viewUUID=="string"?i.viewUUID:void 0,l=De("");l.current===""&&(l.current=crypto.randomUUID());let p=Mt((d,u)=>{ne()&&At(a,l.current);try{Promise.resolve(n.current(d)).catch(c=>{console.error("[unstable_useSendFollowUpWithGhostGuard]",c)})}catch(c){console.error("[unstable_useSendFollowUpWithGhostGuard]",c)}},[a]),f=Rt(()=>{let d=l.current;return function({children:c}){if(!ne())return te(Ne,{children:c});let y=Wt(a);return y&&y.byMountId!==d&&Date.now()-y.at<Ot?te(Nt,{}):te(Ne,{children:c})}},[a]);return{sendFollowUp:p,Guard:f}}import{useCallback as Lt}from"react";import H,{useCallback as _e,useContext as Ft,useEffect as Le,useState as oe,useSyncExternalStore as _t}from"react";function ie({children:e,loading:t=null,onError:n}){let[r,o]=oe(null),[i,a]=oe(null),[l,p]=oe(!0);return Le(()=>{let f=!0,d=null;async function u(){try{let c=await Re();await c.connect(),f?(d=c,o(c),p(!1)):c.close()}catch(c){f&&(console.error("error",c),a(c instanceof Error?c:new Error(String(c))),p(!1))}}return u(),()=>{f=!1,d?.close()}},[]),Le(()=>{if(!r)return;let f=d=>{document.documentElement.classList.toggle("dark",d==="dark"),document.documentElement.style.colorScheme=d==="dark"?"dark":"auto"};return f(r.getTheme()),r.onThemeChange(f)},[r]),i&&n?H.createElement(H.Fragment,null,n(i)):l||!r?H.createElement(H.Fragment,null,t):H.createElement(E.Provider,{value:r},e)}function m(e){let t=Ft(E);if(!t)throw new Error("useWidgetClient must be used within a WidgetProvider");let n=_e(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]),r=_e(()=>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]),o=_t(n,r,r);return e?o:t}function se(){let e=m();return Lt((t,n)=>e.callTool(t,n),[e])}function ae(){return m("displayMode")}function V(){return m("toolOutput")}function le(){return{data:V()}}import{useSyncExternalStore as Pt}from"react";function de(){return Pt(()=>()=>{},()=>typeof window>"u"?!1:window.__isChatGptApp===!0,()=>!1)}function ue(){return m("locale")}function ce(){return m("maxHeight")}import{useCallback as Bt}from"react";function pe(){let e=m();return Bt(t=>e.openExternal(t),[e])}import{useCallback as Gt}from"react";function fe(){let e=m();return Gt(t=>e.requestDisplayMode(t),[e])}function ge(){return m("safeArea")}import{useCallback as Ht}from"react";function me(){let e=m();return Ht((t,n)=>{(async()=>{Ee(n?.modelContext)&&await Promise.resolve(e.updateModelContext(n.modelContext)),await Promise.resolve(e.sendFollowUp(t))})().catch(r=>{console.error("Failed to send follow-up message:",r)})},[e])}function he(){return m("theme")}function we(){return m("toolResponseMetadata")}import{useCallback as Vt}from"react";function ye(){let e=m();return Vt(async t=>{await Promise.resolve(e.updateModelContext(t))},[e])}import{useCallback as jt,useEffect as Kt,useState as qt}from"react";function ve(e){let t=m("widgetState"),[n,r]=qt(()=>t??(typeof e=="function"?e():e??null));Kt(()=>{r(t)},[t]);let o=jt(i=>{r(a=>{let l=typeof i=="function"?i(a):i;return K()==="openai"&&l!=null&&window.openai?.setWidgetState(l),l})},[]);return[n,o]}import{jsx as R,jsxs as Pe}from"react/jsx-runtime";var Be=()=>Pe("div",{className:"flex flex-col items-center justify-center h-full min-h-[120px] gap-4",children:[Pe("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(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: ",q,"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:`${q}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=",q,"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:`
|
|
63
63
|
@keyframes shimmer {
|
|
64
64
|
0% { background-position: 200% 0; }
|
|
65
65
|
100% { background-position: -200% 0; }
|
|
66
66
|
}
|
|
67
|
-
`})]});import{useContext as wn,useEffect as Se,useMemo as yn,useRef as vn,useState as Te}from"react";function F(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var zt=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],Yt=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],$t=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],Jt=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],Xt=["waniwani/visitorId","visitorId"],Zt=["correlationId","openai/requestId"];var xe="waniwani/widget";function Ge(e){return e?F(e,zt):void 0}function He(e){return e?F(e,Yt):void 0}function Ve(e){return e?F(e,$t):void 0}function je(e){return e?F(e,Jt):void 0}function Ke(e){return e?F(e,Xt):void 0}function qe(e){return e?F(e,Zt):void 0}var Qt=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],en=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function ze(e,t){if(e){let r=e["waniwani/source"];if(typeof r=="string"&&r.length>0)return r;for(let{key:o,source:i}of Qt){let a=e[o];if(typeof a=="string"&&a.length>0)return i}}let n=t?.name;if(typeof n=="string"&&n.length>0){let r=n.toLowerCase();for(let{needle:o,source:i}of en)if(r.includes(o))return i}}var tn="@waniwani/sdk";function Ye(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??nn,o=sn(e),i=z(e.meta),a=z(e.metadata),l=an(e,i),p=v(e.eventId)??r(),f=ln(e.timestamp,n),d=v(e.source)??ze(i)??t.source??tn,u=be(e)?{...e}:void 0,c={...a};return Object.keys(i).length>0&&(c.meta=i),u&&(c.rawLegacy=u),{id:p,type:"mcp.event",name:o,source:d,timestamp:f,correlation:l,properties:rn(e,o),metadata:c,rawLegacy:u}}function nn(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function rn(e,t){if(!be(e))return z(e.properties);let n=on(e,t),r=z(e.properties);return{...n,...r}}function on(e,t){switch(t){case"tool.called":{let n={};return v(e.toolName)&&(n.name=e.toolName),v(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),v(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return v(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),v(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function sn(e){return be(e)?e.eventType:e.event}function an(e,t){let n=v(e.requestId)??He(t),r=v(e.sessionId)??Ge(t),o=v(e.traceId)??Ve(t),i=v(e.externalUserId)??je(t),a=v(e.visitorId)??Ke(t),l=v(e.correlationId)??qe(t)??n,p={};return r&&(p.sessionId=r),o&&(p.traceId=o),n&&(p.requestId=n),l&&(p.correlationId=l),i&&(p.externalUserId=i),a&&(p.visitorId=a),p}function ln(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 z(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function v(e){if(typeof e=="string"&&e.trim().length!==0)return e}function be(e){return"eventType"in e}function $e(e){return{priceShown:({amount:t,currency:n,itemId:r,label:o,...i})=>e({event:"price_shown",properties:{amount:t,currency:n,itemId:r,label:o},...i}),pricesCompared:({options:t,...n})=>e({event:"prices_compared",properties:{options:t},...n}),optionSelected:({id:t,amount:n,currency:r,...o})=>e({event:"option_selected",properties:{id:t,amount:n,currency:r},...o}),leadQualified:t=>{let{externalId:n,email:r,name:o,...i}=t??{};return e({event:"lead_qualified",properties:{externalId:n,email:r,name:o},...i})},converted:({amount:t,currency:n,occurredAt:r,...o})=>e({event:"converted",properties:{amount:t,currency:n,occurredAt:r},...o})}}var dn="/api/mcp/events/v2/batch";var Je="@waniwani/sdk";var un=new Set([401,403]),cn=new Set([408,425,429,500,502,503,504]);function Xe(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=gn(t.apiUrl,t.endpointPath??dn),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(r=>setTimeout(r,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,r=this.flush();if(!Number.isFinite(n)||n<=0)return await r,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let o=Symbol("shutdown-timeout");return await Promise.race([r.then(()=>"flushed"),this.sleep(n).then(()=>o)])===o?(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 r=Math.ceil(t.length/2);this.sendKeepaliveChunk(t.slice(0,r)),this.sendKeepaliveChunk(t.slice(r));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":Je};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,r=t;for(;r.length>0&&!this.isStopped;){this.inFlightCount=r.length;let o=await this.sendBatchOnce(r);switch(this.inFlightCount=0,o.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(o.status,r.length);return;case"permanent":this.logger.error("[Waniwani] Dropping %d event(s) after permanent failure: %s",r.length,o.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d event(s) after retry exhaustion: %s",r.length,o.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(o.permanent.length>0&&this.logger.error("[Waniwani] Dropping %d event(s) rejected as permanent",o.permanent.length),o.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d retryable event(s) after retry exhaustion",o.retryable.length);return}r=o.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:mn(i)}}if(un.has(n.status))return{kind:"auth",status:n.status};if(cn.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await fn(n);if(!r?.rejected||r.rejected.length===0)return{kind:"success"};let o=this.classifyRejectedEvents(t,r.rejected);return o.retryable.length===0&&o.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:o.retryable,permanent:o.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:Je,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let r=new Map(t.map(a=>[a.id,a])),o=[],i=[];for(let a of n){let l=r.get(a.eventId);if(l){if(pn(a)){o.push(l);continue}i.push(l)}}return{retryable:o,permanent:i}}backoffDelayMs(t){let n=this.retryBaseDelayMs*2**t;return Math.min(n,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,n){this.isStopped=!0;let r=this.buffer.length;this.buffer.splice(0,r),this.logger.error("[Waniwani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,n+r)}};function pn(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 fn(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function gn(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function mn(e){return e instanceof Error?e.message:String(e)}function Ze(e){let{apiUrl:t,endpointPath:n}=hn(e.endpoint),r=Xe({apiUrl:t,apiKey:e.token,endpointPath:n,flushIntervalMs:e.flushIntervalMs}),o,i=l=>typeof l=="function"?l():l,a=async l=>{let p=e.identity?.()??{},f=i(e.channelId),d=f===void 0?l.properties:{channelId:f,...l.properties},u=Ye({sessionId:p.sessionId,visitorId:p.visitorId,externalUserId:p.externalUserId??o,traceId:p.traceId,...l,properties:d,metadata:{...e.metadata,...l.metadata}},{source:i(e.source)});return r.enqueue(u),{eventId:u.id}};return{track:Object.assign(a,$e(a)),identify(l,p){return o=l,a({event:"user.identified",externalUserId:l,properties:p})},flush:()=>r.flush(),shutdown:l=>r.shutdown(l)}}function hn(e){let t=new URL(e);return{apiUrl:t.origin,endpointPath:`${t.pathname}${t.search}`}}var U=async()=>({eventId:""});function xn(){return Object.assign(U,{priceShown:U,pricesCompared:U,optionSelected:U,leadQualified:U,converted:U})}var Qe={sessionId:void 0,track:xn(),identify:U,flush:async()=>{}},Y=null,$=0;function M(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function et(e){if(!e)return null;let t=e.getToolResponseMetadata();if(!t)return null;let n=t._meta,r=t[xe]??n?.[xe],o=M(r?.endpoint);return o?{endpoint:o,token:M(r?.token),sessionId:M(r?.sessionId),source:M(r?.source)}:null}function tt(e,t){return e?.endpoint===t?.endpoint&&e?.token===t?.token&&e?.sessionId===t?.sessionId&&e?.source===t?.source}function bn(e){let t=wn(E),[n,r]=Te(null);return Se(()=>{if(e||t||typeof window>"u")return;let o=!0,i=null;return(async()=>{try{let{createWidgetClient:a}=await import("../widget-client-4MBLDRHD.js"),l=await a();if(await l.connect(),!o){l.close();return}i=l,r(l)}catch{}})(),()=>{o=!1,i?.close(),r(null)}},[e,t]),t??n}function kn(e){let[t,n]=Te(()=>et(e));return Se(()=>{if(!e){n(o=>o===null?o:null);return}let r=()=>{let o=et(e);n(i=>tt(i,o)?i:o)};return r(),e.onToolResponseMetadataChange(()=>{r()})},[e]),t}function Sn(e,t){let n=e.sessionId??crypto.randomUUID(),r=crypto.randomUUID(),o=Ze({endpoint:e.endpoint,token:e.token,source:e.source,identity:()=>({sessionId:n,traceId:r}),metadata:t});return o.track({event:"widget_render"}),{config:e,widget:{sessionId:n,track:o.track,identify:(i,a)=>o.identify(i,a),flush:()=>o.flush()},cleanup:()=>{o.shutdown()}}}function nt(e={}){let t=M(e.endpoint),n=M(e.token),r=M(e.sessionId),o=M(e.source),i=bn(!!t),a=kn(i),l=yn(()=>{let u=o??a?.source;return u?t?{endpoint:t,token:n??a?.token,sessionId:r??a?.sessionId,source:u}:a?{...a,token:n??a.token,sessionId:r??a.sessionId,source:u}:null:null},[t,n,r,o,a]),[p,f]=Te(Qe),d=vn(e.metadata);return d.current=e.metadata,Se(()=>{if(typeof window>"u")return;if(!l){f(Qe);return}let u=Y;return(!u||!tt(u.config,l))&&(u?.cleanup(),u=Sn(l,d.current),Y=u),f(u.widget),$++,()=>{$=Math.max($-1,0),$===0&&(Y?.cleanup(),Y=null)}},[l]),p}export{ee as DevModeProvider,Ue as InitializeNextJsInIframe,Be as LoadingWidget,ie as WidgetProvider,K as detectPlatform,G as getMockState,O as initializeMockOpenAI,Ce as isMCPApps,Me as isOpenAI,re as unstable_useSendFollowUpWithGhostGuard,A as updateMockDisplayMode,I as updateMockGlobal,D as updateMockTheme,W 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,V as useToolOutput,we as useToolResponseMetadata,ye as useUpdateModelContext,nt 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 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"],qt=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],zt=["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,qt):void 0}function Ge(e){return e?F(e,zt):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 qe(e,t={}){let n=t.now??(()=>new Date),o=t.generateId??Zt,r=tn(e),i=z(e.meta),d=z(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 z(e.properties);let n=en(e,t),o=z(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"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),x(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return x(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),x(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),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 z(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 ze(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=qe({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,ze(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};
|
|
68
68
|
//# sourceMappingURL=react.js.map
|