@waniwani/sdk 0.12.1 → 0.12.2
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/legacy/index.d.ts +87 -15
- package/dist/legacy/index.js +13 -13
- package/dist/legacy/index.js.map +1 -1
- package/dist/legacy/mcp/react.d.ts +87 -15
- package/dist/legacy/mcp/react.js +7 -7
- package/dist/legacy/mcp/react.js.map +1 -1
- package/dist/mcp/react.d.ts +87 -15
- package/dist/mcp/react.js +7 -7
- package/dist/mcp/react.js.map +1 -1
- package/package.json +1 -1
package/dist/mcp/react.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
2
|
import { ContentBlock, CallToolResult } from '@modelcontextprotocol/sdk/types.js';
|
|
3
|
-
import React$1, { ReactNode, SetStateAction } from 'react';
|
|
3
|
+
import React$1, { ReactNode, JSX, SetStateAction } from 'react';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Initializes & patches Next.js functionality so an app can run as a
|
|
@@ -140,6 +140,91 @@ type ModelContextUpdate = {
|
|
|
140
140
|
structuredContent?: Record<string, unknown>;
|
|
141
141
|
};
|
|
142
142
|
|
|
143
|
+
interface SendFollowUpOptions {
|
|
144
|
+
modelContext?: ModelContextUpdate | null;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Get a function to send follow-up messages to the AI.
|
|
148
|
+
* Works on both OpenAI widgets and MCP Apps.
|
|
149
|
+
*
|
|
150
|
+
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
151
|
+
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
152
|
+
* @returns A function that sends a follow-up message
|
|
153
|
+
*/
|
|
154
|
+
declare function useSendFollowUp(): (prompt: string, options?: SendFollowUpOptions) => void;
|
|
155
|
+
|
|
156
|
+
interface UnstableSendFollowUpWithGhostGuardResult {
|
|
157
|
+
/** Wrapped `sendFollowUp`. Same signature as the one you passed in. */
|
|
158
|
+
sendFollowUp: (prompt: string, options?: SendFollowUpOptions) => void;
|
|
159
|
+
/**
|
|
160
|
+
* Wrap your widget's root render with this so the suppression can take
|
|
161
|
+
* effect. On non-ChatGPT hosts it is a transparent pass-through.
|
|
162
|
+
*/
|
|
163
|
+
Guard: (props: {
|
|
164
|
+
children: ReactNode;
|
|
165
|
+
}) => JSX.Element | null;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* ⚠️ EXPERIMENTAL — DO NOT USE UNLESS YOU UNDERSTAND THE TRADE-OFFS ⚠️
|
|
169
|
+
*
|
|
170
|
+
* Wraps an existing `sendFollowUp` with ghost-guard suppression specific
|
|
171
|
+
* to ChatGPT. ChatGPT renders the source widget a SECOND time alongside
|
|
172
|
+
* the new user message a widget emits via `sendFollowUpMessage`. The
|
|
173
|
+
* second iframe is a brand-new React tree with no link to the original;
|
|
174
|
+
* skybridge's `useViewState` persistence does not survive across them.
|
|
175
|
+
* The result is a visible duplicate widget for ~1s before ChatGPT
|
|
176
|
+
* collapses one of them.
|
|
177
|
+
*
|
|
178
|
+
* On ChatGPT the hook adds a per-`viewUUID` `localStorage` write before
|
|
179
|
+
* each `sendFollowUp` call, and the returned `Guard` checks that record
|
|
180
|
+
* on mount — if it sees a record set by a different `mountId` within
|
|
181
|
+
* `ADVANCED_WINDOW_MS`, it collapses the iframe to 0×0.
|
|
182
|
+
*
|
|
183
|
+
* On every other host (WaniWani embed, MCP Apps, etc.) the hook is a
|
|
184
|
+
* pure pass-through: `sendFollowUp` is your function unchanged and
|
|
185
|
+
* `Guard` is a transparent fragment.
|
|
186
|
+
*
|
|
187
|
+
* The hook does NOT require `WidgetProvider`. It reads the widget's
|
|
188
|
+
* `viewUUID` from `WidgetClientContext` when one is available and falls
|
|
189
|
+
* back to `window.openai.toolResponseMetadata.viewUUID` otherwise.
|
|
190
|
+
*
|
|
191
|
+
* Caveats:
|
|
192
|
+
* - Relies on ChatGPT's widget iframes sharing a single `localStorage`
|
|
193
|
+
* scope — verified at the time of writing but not guaranteed.
|
|
194
|
+
* - 10s suppression window per `viewUUID`. Two unrelated `sendFollowUp`
|
|
195
|
+
* calls inside 10s with the same viewUUID could mistakenly suppress one.
|
|
196
|
+
* - The `Guard` MUST wrap the widget's root render. If you forget it,
|
|
197
|
+
* the localStorage write happens but nothing is suppressed.
|
|
198
|
+
*
|
|
199
|
+
* @param sendFollowUp - The underlying `sendFollowUp` to wrap. On ChatGPT the
|
|
200
|
+
* hook adds the per-`viewUUID` localStorage write before delegating; on any
|
|
201
|
+
* other host the hook is a pure pass-through. Typically the value of
|
|
202
|
+
* `useSendFollowUpMessage()` from `skybridge/web` or `useSendFollowUp()`
|
|
203
|
+
* from this module.
|
|
204
|
+
*
|
|
205
|
+
* @example
|
|
206
|
+
* function MyWidget() {
|
|
207
|
+
* const sendFollowUpMessage = useSendFollowUpMessage(); // skybridge/web
|
|
208
|
+
* const { sendFollowUp, Guard } =
|
|
209
|
+
* unstable_useSendFollowUpWithGhostGuard(sendFollowUpMessage);
|
|
210
|
+
*
|
|
211
|
+
* // The Guard MUST wrap the widget's root render, otherwise the ghost
|
|
212
|
+
* // iframe will not be suppressed.
|
|
213
|
+
* return (
|
|
214
|
+
* <Guard>
|
|
215
|
+
* <div className="my-widget">
|
|
216
|
+
* <button onClick={() => sendFollowUp("I uploaded my bill")}>
|
|
217
|
+
* Continue
|
|
218
|
+
* </button>
|
|
219
|
+
* </div>
|
|
220
|
+
* </Guard>
|
|
221
|
+
* );
|
|
222
|
+
* }
|
|
223
|
+
*
|
|
224
|
+
* @experimental Subject to change or removal without notice.
|
|
225
|
+
*/
|
|
226
|
+
declare function unstable_useSendFollowUpWithGhostGuard(sendFollowUp: (prompt: string) => void | Promise<void>): UnstableSendFollowUpWithGhostGuardResult;
|
|
227
|
+
|
|
143
228
|
/**
|
|
144
229
|
* Result from calling a tool
|
|
145
230
|
*/
|
|
@@ -398,19 +483,6 @@ declare function useRequestDisplayMode(): (mode: DisplayMode) => Promise<Display
|
|
|
398
483
|
*/
|
|
399
484
|
declare function useSafeArea(): SafeArea | null;
|
|
400
485
|
|
|
401
|
-
interface SendFollowUpOptions {
|
|
402
|
-
modelContext?: ModelContextUpdate | null;
|
|
403
|
-
}
|
|
404
|
-
/**
|
|
405
|
-
* Get a function to send follow-up messages to the AI.
|
|
406
|
-
* Works on both OpenAI widgets and MCP Apps.
|
|
407
|
-
*
|
|
408
|
-
* @deprecated Legacy MCP-widget-in-host stack. Preserved for back-compat; will move to
|
|
409
|
-
* `@waniwani/sdk/legacy/react` in a future minor release.
|
|
410
|
-
* @returns A function that sends a follow-up message
|
|
411
|
-
*/
|
|
412
|
-
declare function useSendFollowUp(): (prompt: string, options?: SendFollowUpOptions) => void;
|
|
413
|
-
|
|
414
486
|
/**
|
|
415
487
|
* Get the current theme.
|
|
416
488
|
* Works on both OpenAI widgets and MCP Apps.
|
|
@@ -657,4 +729,4 @@ interface WaniwaniWidget {
|
|
|
657
729
|
*/
|
|
658
730
|
declare function useWaniwani(options?: UseWaniwaniOptions): WaniwaniWidget;
|
|
659
731
|
|
|
660
|
-
export { DevModeProvider, type DeviceType, type DisplayMode, type FlowActionResult, type HostContext, InitializeNextJsInIframe, LoadingWidget, type ModelContextContentBlock, type ModelContextUpdate, type SafeArea, type SafeAreaInsets, type SendFollowUpOptions, type Theme, type ToolCallResult, type ToolResult, type UnifiedWidgetClient, type UnknownObject, type UseWaniwaniOptions, type UserAgent, type WaniwaniWidget, type WidgetPlatform, WidgetProvider, detectPlatform, getMockState, initializeMockOpenAI, isMCPApps, isOpenAI, updateMockDisplayMode, updateMockGlobal, updateMockTheme, updateMockToolOutput, useCallTool, useDisplayMode, useFlowAction, useIsChatGptApp, useLocale, useMaxHeight, useOpenExternal, useRequestDisplayMode, useSafeArea, useSendFollowUp, useTheme, useToolOutput, useToolResponseMetadata, useUpdateModelContext, useWaniwani, useWidgetClient, useWidgetState };
|
|
732
|
+
export { DevModeProvider, type DeviceType, type DisplayMode, type FlowActionResult, type HostContext, InitializeNextJsInIframe, LoadingWidget, type ModelContextContentBlock, type ModelContextUpdate, type SafeArea, type SafeAreaInsets, type SendFollowUpOptions, type Theme, type ToolCallResult, type ToolResult, type UnifiedWidgetClient, type UnknownObject, type UnstableSendFollowUpWithGhostGuardResult, type UseWaniwaniOptions, type UserAgent, type WaniwaniWidget, type WidgetPlatform, WidgetProvider, detectPlatform, getMockState, initializeMockOpenAI, isMCPApps, isOpenAI, unstable_useSendFollowUpWithGhostGuard, updateMockDisplayMode, updateMockGlobal, updateMockTheme, updateMockToolOutput, useCallTool, useDisplayMode, useFlowAction, useIsChatGptApp, useLocale, useMaxHeight, useOpenExternal, useRequestDisplayMode, useSafeArea, useSendFollowUp, useTheme, useToolOutput, useToolResponseMetadata, useUpdateModelContext, useWaniwani, useWidgetClient, useWidgetState };
|
package/dist/mcp/react.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{a as
|
|
2
|
+
import{a as V,b as Me,c as Se}from"../chunk-DP6SAQTK.js";import{b as H,c as Te}from"../chunk-RZKVTH7F.js";import{Fragment as nt,jsx as B,jsxs as ot}from"react/jsx-runtime";function et(){let e=window.innerBaseUrl,t=window.__wwPassthroughOrigins??[],n=document.documentElement;new MutationObserver(p=>{p.forEach(g=>{if(g.type==="attributes"&&g.target===n){let c=g.attributeName;c&&c!=="suppresshydrationwarning"&&c!=="lang"&&c!=="class"&&c!=="style"&&n.removeAttribute(c)}})}).observe(n,{attributes:!0,attributeOldValue:!0});let r=history.replaceState.bind(history);history.replaceState=(p,g,c)=>{try{let s=new URL(String(c??""),window.location.href);r(null,g,s.pathname+s.search+s.hash)}catch{}};let u=history.pushState.bind(history);history.pushState=(p,g,c)=>{try{let s=new URL(String(c??""),window.location.href);u(null,g,s.pathname+s.search+s.hash)}catch{}};let f=new URL(e).origin,w=window.self!==window.top;if(window.addEventListener("click",p=>{let g=p?.target?.closest("a");if(!g||!g.href)return;let c=new URL(g.href,window.location.href);if(c.origin!==window.location.origin&&c.origin!==f)try{window.openai&&(window.openai?.openExternal({href:g.href}),p.preventDefault())}catch{console.warn("openExternal failed, likely not in OpenAI client")}},!0),w&&window.location.origin!==f){let p=window.fetch;window.fetch=((o,l)=>{let m=typeof o=="string"&&!/^[a-z][a-z0-9+.-]*:/i.test(o)&&!o.startsWith("//"),d;if(typeof o=="string"||o instanceof URL?d=new URL(o,window.location.href):d=new URL(o.url,window.location.href),d.origin===f)return typeof o=="string"||o instanceof URL?o=d.toString():o=new Request(d.toString(),o),p.call(window,o,{...l,mode:"cors"});if(t.indexOf(d.origin)!==-1)return p.call(window,o,l);if(m&&d.origin===window.location.origin){let x=new URL(e);return x.pathname=d.pathname,x.search=d.search,x.hash=d.hash,d=x,o=d.toString(),p.call(window,o,{...l,mode:"cors"})}return p.call(window,o,l)});let g=f.replace(/^http/,"ws"),c=window.WebSocket,s=((o,l)=>{let m=new URL(String(o),window.location.href);if(m.origin===window.location.origin||m.origin===window.location.origin.replace(/^http/,"ws")){let d=new URL(g);return d.pathname=m.pathname,d.search=m.search,d.hash=m.hash,new c(d.toString(),l)}return new c(o,l)});s.prototype=c.prototype,Object.assign(s,{CONNECTING:c.CONNECTING,OPEN:c.OPEN,CLOSING:c.CLOSING,CLOSED:c.CLOSED}),window.WebSocket=s}}var tt=`(${et.toString()})()`;function Ee({baseUrl:e,passthroughOrigins:t}){return ot(nt,{children:[B("base",{href:e}),B("script",{children:`window.innerBaseUrl = ${JSON.stringify(e)}`}),B("script",{children:`window.__wwPassthroughOrigins = ${JSON.stringify(t??[])}`}),B("script",{children:'window.__isChatGptApp = typeof window.openai !== "undefined";'}),B("script",{children:tt})]})}import{useCallback as T,useEffect as F,useRef as Z,useState as C}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},G={...Re};function U(e){typeof window>"u"||window.openai||(G={...Re,toolOutput:e??null},window.openai={...G,requestDisplayMode:async({mode:t})=>(R("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=>{R("widgetState",t)}},window.dispatchEvent(new H({globals:G})))}function R(e,t){typeof window>"u"||!window.openai||(G[e]=t,window.openai[e]=t,window.dispatchEvent(new H({globals:{[e]:t}})))}function j(){return{...G}}function N(e){R("toolOutput",e)}function L(e){R("displayMode",e)}function D(e){R("theme",e)}import{Fragment as Q,jsx as a,jsxs as y}from"react/jsx-runtime";var $=150;function We({className:e}){return y("svg",{className:e,viewBox:"0 0 24 24",fill:"none",role:"img","aria-label":"Dev Controls",children:[a("rect",{x:"4",y:"4",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5"}),a("rect",{x:"10",y:"10",width:"10",height:"10",rx:"2",stroke:"currentColor",strokeWidth:"1.5",fill:"currentColor",fillOpacity:"0.15"})]})}function rt({className:e}){return a("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:a("path",{d:"M18 6L6 18M6 6l12 12"})})}function it({className:e}){return a("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:a("rect",{x:"2",y:"4",width:"12",height:"8",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"})})}function st({className:e}){return y("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[a("rect",{x:"1.5",y:"3",width:"13",height:"10",rx:"1.5",stroke:"currentColor",strokeWidth:"1.25"}),a("rect",{x:"8.5",y:"7",width:"5",height:"4",rx:"0.75",fill:"currentColor"})]})}function at({className:e}){return a("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:a("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 lt({className:e}){return y("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[a("circle",{cx:"8",cy:"8",r:"2.5",stroke:"currentColor",strokeWidth:"1.25"}),a("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 dt({className:e}){return a("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:a("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 ut({className:e}){return y("svg",{"aria-hidden":"true",className:e,viewBox:"0 0 16 16",fill:"none",children:[a("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"}),a("path",{d:"M12.5 2v3h-3M3.5 14v-3h3",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})]})}var ct=`
|
|
3
3
|
@keyframes devPanelSlideIn {
|
|
4
4
|
0% {
|
|
5
5
|
opacity: 0;
|
|
@@ -47,22 +47,22 @@ import{a as Y,b as be,c as ke}from"../chunk-DP6SAQTK.js";import{b as P,c as Ce}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[
|
|
50
|
+
`;function ee({defaultProps:e,widgetPaths:t,children:n}){let[i,r]=C(!1),[u,f]=C(!1);return F(()=>{if(new URLSearchParams(window.location.search).get("platform")==="mcp-apps"){r(!0);return}if(t&&t.length>0){let p=window.location.pathname,g=t.some(c=>p===c||p.startsWith(`${c}/`));f(g),g&&U(e)}else U(e),f(!0);r(!0)},[e,t]),i?u?y(Q,{children:[a(pt,{children:n}),a(gt,{defaultProps:e})]}):a(Q,{children:n}):null}function pt({children:e}){return a("div",{className:"min-h-screen bg-[#212121] flex items-center justify-center p-8",children:a("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 _e({options:e,value:t,onChange:n}){let i=e.findIndex(r=>r.value===t);return y("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:[a("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(${i*100}% + ${i*2}px))`,background:"rgba(255, 255, 255, 0.1)"}}),e.map(r=>y("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,a("span",{className:"capitalize",children:r.label})]},r.value))]})}function gt({defaultProps:e}){let[t,n]=C(()=>typeof window>"u"?!1:localStorage.getItem("dev-controls-open")==="true"),[i,r]=C(!1),[u,f]=C(t),[w,p]=C("inline"),[g,c]=C("dark"),[s,o]=C(!1),[l,m]=C(()=>JSON.stringify(e??{},null,2)),[d,x]=C(null),b=Z(null),E=Z(null),P=Z(null);F(()=>{let h=j();p(h.displayMode),c(h.theme)},[]),F(()=>{typeof window>"u"||(window.openai||(window.openai={}),window.openai.safeArea={insets:{top:0,bottom:s?$:0,left:0,right:0}},window.dispatchEvent(new H({globals:{safeArea:window.openai.safeArea}})))},[s]),F(()=>{localStorage.setItem("dev-controls-open",String(t))},[t]);let O=T(()=>{f(!0),requestAnimationFrame(()=>{n(!0)})},[]),W=T(()=>{r(!0),n(!1),setTimeout(()=>{f(!1),r(!1)},150)},[]),q=T(()=>{t?W():O()},[t,O,W]);F(()=>{let h=k=>{(k.metaKey||k.ctrlKey)&&k.shiftKey&&k.key==="d"&&(k.preventDefault(),q()),k.key==="Escape"&&t&&W()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t,q,W]),F(()=>{if(!t)return;let h=k=>{P.current&&!P.current.contains(k.target)&&W()};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[t,W]);let Ve=T(h=>{p(h),L(h)},[]),$e=T(h=>{c(h),D(h)},[]),J=T(h=>{try{let k=JSON.parse(h);x(null),N(k)}catch{x("Invalid JSON")}},[]),Xe=T(h=>{m(h),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{J(h)},500)},[J]),Ye=T(()=>{b.current&&clearTimeout(b.current),J(l)},[J,l]),qe=T(()=>{let h=JSON.stringify(e??{},null,2);m(h),x(null),N(e??{}),p("inline"),L("inline"),c("dark"),D("dark")},[e]),Ze=[{value:"inline",label:"inline",icon:a(it,{className:"w-3.5 h-3.5"})},{value:"pip",label:"pip",icon:a(st,{className:"w-3.5 h-3.5"})},{value:"fullscreen",label:"full",icon:a(at,{className:"w-3.5 h-3.5"})}],Qe=[{value:"light",label:"light",icon:a(lt,{className:"w-3.5 h-3.5"})},{value:"dark",label:"dark",icon:a(dt,{className:"w-3.5 h-3.5"})}];return y(Q,{children:[a("style",{dangerouslySetInnerHTML:{__html:ct}}),y("div",{ref:P,className:"fixed bottom-4 right-4 z-[9999] font-['Inter',_system-ui,_sans-serif]",children:[y("button",{type:"button",onClick:q,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:[a(
|
|
58
|
+
`},"aria-label":"Toggle Dev Controls","aria-expanded":t,children:[a(We,{className:`w-5 h-5 transition-all duration-200 ${t?"text-indigo-400 scale-110":"text-gray-300 group-hover:text-white"}`}),a("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%)"}})]}),u&&y("div",{ref:E,className:`absolute bottom-14 right-0 w-80 ${t&&!i?"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:[v("div",{className:"flex items-center justify-between px-4 py-3",style:{borderBottom:"1px solid rgba(255, 255, 255, 0.06)"},children:[v("div",{className:"flex items-center gap-2",children:[a(Te,{className:"w-4 h-4 text-gray-400"}),a("span",{className:"text-sm font-medium text-white",children:"Dev Controls"})]}),v("div",{className:"flex items-center gap-2",children:[a("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"}),a("button",{type:"button",onClick:W,className:"p-1 rounded-md text-gray-500 hover:text-gray-300 hover:bg-white/5 transition-colors",children:a(Ze,{className:"w-4 h-4"})})]})]}),v("div",{className:"p-4 space-y-5 overflow-y-auto",style:{maxHeight:"calc(100vh - 200px)"},children:[v("div",{children:[a("label",{htmlFor:"display-mode",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Display Mode"}),a(Ee,{options:Ve,value:x,onChange:Be})]}),v("div",{children:[a("label",{htmlFor:"theme",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Theme"}),a(Ee,{options:Ye,value:m,onChange:je})]}),v("div",{children:[a("label",{htmlFor:"safe-area",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Safe Area (Chat Input)"}),v("button",{type:"button",onClick:()=>o(!r),className:`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-xs font-medium transition-all duration-150 ${r?"text-emerald-400":"text-gray-400"}`,style:{background:r?"rgba(34, 197, 94, 0.1)":"rgba(255, 255, 255, 0.04)",border:r?"1px solid rgba(34, 197, 94, 0.3)":"1px solid rgba(255, 255, 255, 0.06)"},children:[a("span",{children:"Mock ChatGPT Input Bar"}),a("span",{className:`px-2 py-0.5 rounded text-[10px] font-semibold ${r?"bg-emerald-500/20 text-emerald-400":"bg-gray-500/20 text-gray-500"}`,children:r?"ON":"OFF"})]}),r&&v("p",{className:"text-[10px] text-gray-500 mt-1.5",children:["bottom: ",$,"px"]})]}),v("div",{children:[a("label",{htmlFor:"widget-props",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Widget Props"}),a("textarea",{value:d,onChange:f=>Ke(f.target.value),onBlur:ze,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:l?"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:f=>{l||(f.target.style.borderColor="rgba(99, 102, 241, 0.5)")},onBlurCapture:f=>{l||(f.target.style.borderColor="rgba(255, 255, 255, 0.06)")},spellCheck:!1}),l&&v("p",{className:"text-red-400 text-[11px] mt-1.5 flex items-center gap-1",children:[a("svg",{"aria-hidden":"true","aria-label":"Error",className:"w-3 h-3",viewBox:"0 0 16 16",fill:"currentColor",children:a("path",{d:"M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM7 4.5h2v4H7v-4zm0 5h2v2H7v-2z"})}),l]})]}),v("button",{type:"button",onClick:Ge,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:f=>{f.currentTarget.style.background="rgba(255, 255, 255, 0.08)",f.currentTarget.style.borderColor="rgba(255, 255, 255, 0.1)"},onMouseLeave:f=>{f.currentTarget.style.background="rgba(255, 255, 255, 0.04)",f.currentTarget.style.borderColor="rgba(255, 255, 255, 0.06)"},children:[a(it,{className:"w-3.5 h-3.5"}),"Reset to Defaults"]})]})]})]}),r&&v("div",{className:"fixed bottom-0 left-0 right-0 z-[9998] flex items-center justify-center pointer-events-none",style:{height:`${$}px`,background:"linear-gradient(to top, #1a1a1a 0%, #1a1a1a 80%, transparent 100%)"},children:[v("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:[a("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:a("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),a("div",{className:"flex-1 text-gray-400 text-sm",children:"Ask me anything..."}),a("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:a("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a("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"})})})]}),v("div",{className:"absolute bottom-1 text-[10px] text-gray-600 font-mono",children:["Mock SafeArea: bottom=",$,"px"]})]})]})}import{useCallback as ut}from"react";import z,{useCallback as We,useContext as dt,useEffect as _e,useState as te,useSyncExternalStore as ct}from"react";import{createContext as lt}from"react";var K=lt(null);async function Re(){let{detectPlatform:e}=await import("../platform-LKQFC3AJ.js");if(e()==="openai"){let{OpenAIWidgetClient:n}=await import("../openai-client-TZIOCMXP.js");return new n}else{let{MCPAppsWidgetClient:n}=await import("../mcp-apps-client-OFYMQOI3.js");return new n}}function ne({children:e,loading:t=null,onError:n}){let[s,i]=te(null),[c,h]=te(null),[x,p]=te(!0);return _e(()=>{let m=!0,u=null;async function r(){try{let o=await Re();await o.connect(),m?(u=o,i(o),p(!1)):o.close()}catch(o){m&&(console.error("error",o),h(o instanceof Error?o:new Error(String(o))),p(!1))}}return r(),()=>{m=!1,u?.close()}},[]),_e(()=>{if(!s)return;let m=u=>{document.documentElement.classList.toggle("dark",u==="dark"),document.documentElement.style.colorScheme=u==="dark"?"dark":"auto"};return m(s.getTheme()),s.onThemeChange(m)},[s]),c&&n?z.createElement(z.Fragment,null,n(c)):x||!s?z.createElement(z.Fragment,null,t):z.createElement(K.Provider,{value:s},e)}function w(e){let t=dt(K);if(!t)throw new Error("useWidgetClient must be used within a WidgetProvider");let n=We(c=>e==="toolOutput"?t.onToolResult(()=>c()):e==="theme"?t.onThemeChange(()=>c()):e==="displayMode"?t.onDisplayModeChange(()=>c()):e==="safeArea"?t.onSafeAreaChange(()=>c()):e==="maxHeight"?t.onMaxHeightChange(()=>c()):e==="toolResponseMetadata"?t.onToolResponseMetadataChange(()=>c()):e==="widgetState"?t.onWidgetStateChange(()=>c()):()=>{},[t,e]),s=We(()=>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]),i=ct(n,s,s);return e?i:t}function oe(){let e=w();return ut((t,n)=>e.callTool(t,n),[e])}function ie(){return w("displayMode")}function G(){return w("toolOutput")}function re(){return{data:G()}}import{useSyncExternalStore as pt}from"react";function se(){return pt(()=>()=>{},()=>typeof window>"u"?!1:window.__isChatGptApp===!0,()=>!1)}function ae(){return w("locale")}function le(){return w("maxHeight")}import{useCallback as gt}from"react";function de(){let e=w();return gt(t=>e.openExternal(t),[e])}import{useCallback as mt}from"react";function ce(){let e=w();return mt(t=>e.requestDisplayMode(t),[e])}function ue(){return w("safeArea")}import{useCallback as ft}from"react";function pe(){let e=w();return ft((t,n)=>{(async()=>{Ce(n?.modelContext)&&await Promise.resolve(e.updateModelContext(n.modelContext)),await Promise.resolve(e.sendFollowUp(t))})().catch(s=>{console.error("Failed to send follow-up message:",s)})},[e])}function ge(){return w("theme")}function me(){return w("toolResponseMetadata")}import{useCallback as ht}from"react";function fe(){let e=w();return ht(async t=>{await Promise.resolve(e.updateModelContext(t))},[e])}import{useCallback as wt,useEffect as vt,useState as xt}from"react";function he(e){let t=w("widgetState"),[n,s]=xt(()=>t??(typeof e=="function"?e():e??null));vt(()=>{s(t)},[t]);let i=wt(c=>{s(h=>{let x=typeof c=="function"?c(h):c;return Y()==="openai"&&x!=null&&window.openai?.setWidgetState(x),x})},[]);return[n,i]}import{jsx as _,jsxs as Ae}from"react/jsx-runtime";var Oe=()=>Ae("div",{className:"flex flex-col items-center justify-center h-full min-h-[120px] gap-4",children:[Ae("div",{className:"flex gap-2",children:[_("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-blue-400 to-cyan-400 animate-bounce [animation-delay:-0.3s]"}),_("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-cyan-400 to-teal-400 animate-bounce [animation-delay:-0.15s]"}),_("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-teal-400 to-emerald-400 animate-bounce"})]}),_("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..."}),_("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:_("div",{className:"w-16 h-16 rounded-full border-2 border-blue-400/20 animate-ping"})}),_("style",{children:`
|
|
62
|
+
`},children:[y("div",{className:"flex items-center justify-between px-4 py-3",style:{borderBottom:"1px solid rgba(255, 255, 255, 0.06)"},children:[y("div",{className:"flex items-center gap-2",children:[a(We,{className:"w-4 h-4 text-gray-400"}),a("span",{className:"text-sm font-medium text-white",children:"Dev Controls"})]}),y("div",{className:"flex items-center gap-2",children:[a("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"}),a("button",{type:"button",onClick:W,className:"p-1 rounded-md text-gray-500 hover:text-gray-300 hover:bg-white/5 transition-colors",children:a(rt,{className:"w-4 h-4"})})]})]}),y("div",{className:"p-4 space-y-5 overflow-y-auto",style:{maxHeight:"calc(100vh - 200px)"},children:[y("div",{children:[a("label",{htmlFor:"display-mode",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Display Mode"}),a(_e,{options:Ze,value:w,onChange:Ve})]}),y("div",{children:[a("label",{htmlFor:"theme",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Theme"}),a(_e,{options:Qe,value:g,onChange:$e})]}),y("div",{children:[a("label",{htmlFor:"safe-area",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Safe Area (Chat Input)"}),y("button",{type:"button",onClick:()=>o(!s),className:`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-xs font-medium transition-all duration-150 ${s?"text-emerald-400":"text-gray-400"}`,style:{background:s?"rgba(34, 197, 94, 0.1)":"rgba(255, 255, 255, 0.04)",border:s?"1px solid rgba(34, 197, 94, 0.3)":"1px solid rgba(255, 255, 255, 0.06)"},children:[a("span",{children:"Mock ChatGPT Input Bar"}),a("span",{className:`px-2 py-0.5 rounded text-[10px] font-semibold ${s?"bg-emerald-500/20 text-emerald-400":"bg-gray-500/20 text-gray-500"}`,children:s?"ON":"OFF"})]}),s&&y("p",{className:"text-[10px] text-gray-500 mt-1.5",children:["bottom: ",$,"px"]})]}),y("div",{children:[a("label",{htmlFor:"widget-props",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Widget Props"}),a("textarea",{value:l,onChange:h=>Xe(h.target.value),onBlur:Ye,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:d?"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:h=>{d||(h.target.style.borderColor="rgba(99, 102, 241, 0.5)")},onBlurCapture:h=>{d||(h.target.style.borderColor="rgba(255, 255, 255, 0.06)")},spellCheck:!1}),d&&y("p",{className:"text-red-400 text-[11px] mt-1.5 flex items-center gap-1",children:[a("svg",{"aria-hidden":"true","aria-label":"Error",className:"w-3 h-3",viewBox:"0 0 16 16",fill:"currentColor",children:a("path",{d:"M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM7 4.5h2v4H7v-4zm0 5h2v2H7v-2z"})}),d]})]}),y("button",{type:"button",onClick:qe,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:h=>{h.currentTarget.style.background="rgba(255, 255, 255, 0.08)",h.currentTarget.style.borderColor="rgba(255, 255, 255, 0.1)"},onMouseLeave:h=>{h.currentTarget.style.background="rgba(255, 255, 255, 0.04)",h.currentTarget.style.borderColor="rgba(255, 255, 255, 0.06)"},children:[a(ut,{className:"w-3.5 h-3.5"}),"Reset to Defaults"]})]})]})]}),s&&y("div",{className:"fixed bottom-0 left-0 right-0 z-[9998] flex items-center justify-center pointer-events-none",style:{height:`${$}px`,background:"linear-gradient(to top, #1a1a1a 0%, #1a1a1a 80%, transparent 100%)"},children:[y("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:[a("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:a("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),a("div",{className:"flex-1 text-gray-400 text-sm",children:"Ask me anything..."}),a("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:a("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a("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"})})})]}),y("div",{className:"absolute bottom-1 text-[10px] text-gray-600 font-mono",children:["Mock SafeArea: bottom=",$,"px"]})]})]})}import{useCallback as ft,useContext as ht,useLayoutEffect as wt,useMemo as vt,useRef as Ae}from"react";import{createContext as mt}from"react";var _=mt(null);import{Fragment as Ie,jsx as te}from"react/jsx-runtime";var yt="waniwani:send-follow-up:advanced:",xt=1e4;function Oe(e){return`${yt}${e??"default"}`}function bt(e){try{let t=globalThis.localStorage?.getItem(Oe(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 kt(e,t){try{globalThis.localStorage?.setItem(Oe(e),JSON.stringify({at:Date.now(),byMountId:t}))}catch{}}function ne(){return typeof window>"u"?!1:typeof window.openai=="object"}function Ct(){return ne()?window.openai:null}function Mt(){return wt(()=>{let e=document.documentElement,t=document.body,n=e.getAttribute("style"),i=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),i===null?t.removeAttribute("style"):t.setAttribute("style",i)}},[]),null}function oe(e){let t=ht(_),n=Ae(e);n.current=e;let i=t?.getToolResponseMetadata?.()??null,r=Ct()?.toolResponseMetadata??null,u=i??r,f=u&&typeof u.viewUUID=="string"?u.viewUUID:void 0,w=Ae("");w.current===""&&(w.current=crypto.randomUUID());let p=ft((c,s)=>{ne()&&kt(f,w.current);try{Promise.resolve(n.current(c)).catch(o=>{console.error("[unstable_useSendFollowUpWithGhostGuard]",o)})}catch(o){console.error("[unstable_useSendFollowUpWithGhostGuard]",o)}},[f]),g=vt(()=>{let c=w.current;return function({children:o}){if(!ne())return te(Ie,{children:o});let l=bt(f);return l&&l.byMountId!==c&&Date.now()-l.at<xt?te(Mt,{}):te(Ie,{children:o})}},[f]);return{sendFollowUp:p,Guard:g}}import{useCallback as Et}from"react";import K,{useCallback as Ne,useContext as St,useEffect as Le,useState as re,useSyncExternalStore as Tt}from"react";async function Ue(){let{detectPlatform:e}=await import("../platform-LKQFC3AJ.js");if(e()==="openai"){let{OpenAIWidgetClient:n}=await import("../openai-client-TZIOCMXP.js");return new n}else{let{MCPAppsWidgetClient:n}=await import("../mcp-apps-client-OFYMQOI3.js");return new n}}function ie({children:e,loading:t=null,onError:n}){let[i,r]=re(null),[u,f]=re(null),[w,p]=re(!0);return Le(()=>{let g=!0,c=null;async function s(){try{let o=await Ue();await o.connect(),g?(c=o,r(o),p(!1)):o.close()}catch(o){g&&(console.error("error",o),f(o instanceof Error?o:new Error(String(o))),p(!1))}}return s(),()=>{g=!1,c?.close()}},[]),Le(()=>{if(!i)return;let g=c=>{document.documentElement.classList.toggle("dark",c==="dark"),document.documentElement.style.colorScheme=c==="dark"?"dark":"auto"};return g(i.getTheme()),i.onThemeChange(g)},[i]),u&&n?K.createElement(K.Fragment,null,n(u)):w||!i?K.createElement(K.Fragment,null,t):K.createElement(_.Provider,{value:i},e)}function v(e){let t=St(_);if(!t)throw new Error("useWidgetClient must be used within a WidgetProvider");let n=Ne(u=>e==="toolOutput"?t.onToolResult(()=>u()):e==="theme"?t.onThemeChange(()=>u()):e==="displayMode"?t.onDisplayModeChange(()=>u()):e==="safeArea"?t.onSafeAreaChange(()=>u()):e==="maxHeight"?t.onMaxHeightChange(()=>u()):e==="toolResponseMetadata"?t.onToolResponseMetadataChange(()=>u()):e==="widgetState"?t.onWidgetStateChange(()=>u()):()=>{},[t,e]),i=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=Tt(n,i,i);return e?r:t}function se(){let e=v();return Et((t,n)=>e.callTool(t,n),[e])}function ae(){return v("displayMode")}function z(){return v("toolOutput")}function le(){return{data:z()}}import{useSyncExternalStore as Rt}from"react";function de(){return Rt(()=>()=>{},()=>typeof window>"u"?!1:window.__isChatGptApp===!0,()=>!1)}function ue(){return v("locale")}function ce(){return v("maxHeight")}import{useCallback as Wt}from"react";function pe(){let e=v();return Wt(t=>e.openExternal(t),[e])}import{useCallback as _t}from"react";function ge(){let e=v();return _t(t=>e.requestDisplayMode(t),[e])}function me(){return v("safeArea")}import{useCallback as At}from"react";function fe(){let e=v();return At((t,n)=>{(async()=>{Te(n?.modelContext)&&await Promise.resolve(e.updateModelContext(n.modelContext)),await Promise.resolve(e.sendFollowUp(t))})().catch(i=>{console.error("Failed to send follow-up message:",i)})},[e])}function he(){return v("theme")}function we(){return v("toolResponseMetadata")}import{useCallback as It}from"react";function ve(){let e=v();return It(async t=>{await Promise.resolve(e.updateModelContext(t))},[e])}import{useCallback as Ot,useEffect as Ut,useState as Nt}from"react";function ye(e){let t=v("widgetState"),[n,i]=Nt(()=>t??(typeof e=="function"?e():e??null));Ut(()=>{i(t)},[t]);let r=Ot(u=>{i(f=>{let w=typeof u=="function"?u(f):u;return V()==="openai"&&w!=null&&window.openai?.setWidgetState(w),w})},[]);return[n,r]}import{jsx as A,jsxs as De}from"react/jsx-runtime";var Fe=()=>De("div",{className:"flex flex-col items-center justify-center h-full min-h-[120px] gap-4",children:[De("div",{className:"flex gap-2",children:[A("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-blue-400 to-cyan-400 animate-bounce [animation-delay:-0.3s]"}),A("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-cyan-400 to-teal-400 animate-bounce [animation-delay:-0.15s]"}),A("div",{className:"w-3 h-3 rounded-full bg-gradient-to-r from-teal-400 to-emerald-400 animate-bounce"})]}),A("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..."}),A("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:A("div",{className:"w-16 h-16 rounded-full border-2 border-blue-400/20 animate-ping"})}),A("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 Ct,useEffect as xe,useMemo as Mt,useRef as Le,useState as De}from"react";function yt(){return crypto.randomUUID()}function M(e,t,n){return{event_id:yt(),event_type:t,timestamp:new Date().toISOString(),source:e.source??"widget",session_id:e.sessionId,trace_id:e.traceId,...n}}function we(e){let t=e.trim().split(/\s+/),n=t[0]||"",s={};for(let i=1;i<t.length;i++){let c=t[i].indexOf(":");if(c===-1)continue;let h=t[i].slice(0,c),x=t[i].slice(c+1),p=Number(x);s[h]=Number.isFinite(p)&&x!==""?p:x}return{name:n,props:s}}function Ie(e){let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"}function Ne(e,t){let n=[],s=typeof navigator<"u"?navigator:void 0,i=s&&"connection"in s?s.connection:void 0;t([M(e,"widget_render",{metadata:{viewport_width:window.innerWidth,viewport_height:window.innerHeight,device_pixel_ratio:window.devicePixelRatio??1,touch_support:"ontouchstart"in window?1:0,connection_type:i?.effectiveType??"unknown",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}})]);let c=r=>{t([M(e,"widget_error",{metadata:{error_message:r.message,error_stack:(r.error?.stack??"").slice(0,1024),error_source:r.filename??"unknown"}})])};window.addEventListener("error",c),n.push(()=>window.removeEventListener("error",c));let h=r=>{let o=r.reason,d=o instanceof Error?o.message:String(o),g=o instanceof Error?(o.stack??"").slice(0,1024):"";t([M(e,"widget_error",{metadata:{error_message:d,error_stack:g,error_source:"unhandledrejection"}})])};if(window.addEventListener("unhandledrejection",h),n.push(()=>window.removeEventListener("unhandledrejection",h)),e.capture?.click){let r=o=>{let d=o.target,g=d?.closest?.("[data-ww-conversion],[data-ww-step]");if(g){let l=g.getAttribute("data-ww-conversion")??g.getAttribute("data-ww-step")??"";if(we(l).name)return}t([M(e,"widget_click",{metadata:{target_tag:d?.tagName?.toLowerCase()??"unknown",target_id:d?.id||void 0,target_class:d?.className||void 0,click_x:o.clientX,click_y:o.clientY}})])};document.addEventListener("click",r,{capture:!0}),n.push(()=>document.removeEventListener("click",r,{capture:!0}))}let x=r=>{let d=r.target?.closest?.("[data-ww-conversion]");if(!d)return;let{name:g,props:l}=we(d.getAttribute("data-ww-conversion")||"");g&&t([M(e,"conversion",{event_name:g,metadata:Object.keys(l).length>0?l:void 0})])};document.addEventListener("click",x,{capture:!0}),n.push(()=>document.removeEventListener("click",x,{capture:!0}));let p=0,m=r=>{let d=r.target?.closest?.("[data-ww-step]");if(!d)return;let{name:g,props:l}=we(d.getAttribute("data-ww-step")||"");g&&(p++,t([M(e,"step",{event_name:g,step_sequence:p,metadata:Object.keys(l).length>0?l:void 0})]))};document.addEventListener("click",m,{capture:!0}),n.push(()=>document.removeEventListener("click",m,{capture:!0}));let u=r=>{let o=r.target?.closest?.("a");if(!o)return;let d=o.getAttribute("href")??"",g=d.startsWith("http")&&!d.startsWith(window.location.origin);t([M(e,"widget_link_click",{metadata:{href:d,link_text:(o.textContent??"").slice(0,200),is_external:g}})])};if(document.addEventListener("click",u,{capture:!0}),n.push(()=>document.removeEventListener("click",u,{capture:!0})),e.capture?.scroll){let r=null,o=window.scrollY||0,d=()=>{r||(r=setTimeout(()=>{r=null;let g=window.scrollY||document.documentElement.scrollTop,l=document.documentElement.scrollHeight-document.documentElement.clientHeight,y=l>0?Math.round(g/l*100):0,b=g>=o?"down":"up";o=g,t([M(e,"widget_scroll",{metadata:{scroll_depth_pct:y,scroll_direction:b,viewport_height:window.innerHeight}})])},250))};window.addEventListener("scroll",d,{passive:!0}),n.push(()=>{window.removeEventListener("scroll",d),r&&clearTimeout(r)})}if(e.capture?.formField){let r=new WeakMap,o=g=>{let l=g.target;!l||!Ie(l)||r.set(l,Date.now())},d=g=>{let l=g.target;if(!l||!Ie(l))return;let y=r.get(l),b=y?Date.now()-y:0,E=l;t([M(e,"widget_form_field",{metadata:{field_name:E.name||E.id||void 0,field_type:E.type||l.tagName.toLowerCase(),time_in_field_ms:b,filled:!!E.value}})])};document.addEventListener("focusin",o,{capture:!0}),document.addEventListener("focusout",d,{capture:!0}),n.push(()=>{document.removeEventListener("focusin",o,{capture:!0}),document.removeEventListener("focusout",d,{capture:!0})})}if(e.capture?.formSubmit){let r=new WeakMap,o=g=>{let y=g.target?.closest?.("form");y&&!r.has(y)&&r.set(y,Date.now())};document.addEventListener("focusin",o,{capture:!0}),n.push(()=>document.removeEventListener("focusin",o,{capture:!0}));let d=g=>{let l=g.target,y=l?r.get(l):void 0,b=0;if(l){let E=l.querySelectorAll("input, textarea, select");for(let F of E){let O=F;(O.validity&&!O.validity.valid||O.getAttribute("aria-invalid")==="true")&&b++}}t([M(e,"widget_form_submit",{metadata:{form_id:l?.id||void 0,time_to_submit_ms:y?Date.now()-y:void 0,validation_errors:b}})])};document.addEventListener("submit",d,{capture:!0}),n.push(()=>document.removeEventListener("submit",d,{capture:!0}))}return()=>{for(let r of n)r()}}var bt="@waniwani/sdk";function kt(e){let n=e.event_type.startsWith("widget_")?e.event_type:`widget_${e.event_type}`,s={};e.session_id&&(s.sessionId=e.session_id),e.trace_id&&(s.traceId=e.trace_id),e.user_id&&(s.externalUserId=e.user_id);let i={...e.metadata??{}};return e.event_name&&(i.event_name=e.event_name),{id:e.event_id,type:"mcp.event",name:n,source:e.source||"widget",timestamp:e.timestamp,correlation:s,properties:i,metadata:{}}}function ve(e){return JSON.stringify({sentAt:new Date().toISOString(),source:{sdk:bt,version:"0.1.0"},events:e.map(kt)})}var J=class{buffer=[];timer=null;flushing=!1;pendingFlush=!1;stopped=!1;config;teardownVisibility=null;teardownPagehide=null;constructor(t){this.config=t,this.start(),this.registerTeardown()}send(t){if(!this.stopped){if(this.buffer.push(...t),this.buffer.length>200){let n=this.buffer.length-200;this.buffer.splice(0,n)}this.buffer.length>=20&&this.flush().catch(()=>{})}}async flush(){if(!(this.stopped||this.buffer.length===0)){if(this.flushing){this.pendingFlush=!0;return}this.flushing=!0;try{let t=this.buffer.splice(0,20);await this.sendBatch(t)}finally{this.flushing=!1,this.pendingFlush&&this.buffer.length>0&&!this.stopped&&(this.pendingFlush=!1,this.flush().catch(()=>{}))}}}stop(){this.stopped=!0,this.timer&&(clearInterval(this.timer),this.timer=null),typeof document<"u"&&this.teardownVisibility&&(document.removeEventListener("visibilitychange",this.teardownVisibility),this.teardownVisibility=null),typeof window<"u"&&this.teardownPagehide&&(window.removeEventListener("pagehide",this.teardownPagehide),this.teardownPagehide=null)}beaconFlush(){if(this.buffer.length===0)return;let t=[...this.buffer];this.buffer.length=0;let n={"Content-Type":"application/json"};if(this.config.token&&(n.Authorization=`Bearer ${this.config.token}`),typeof fetch<"u"){this.sendKeepAliveChunked(this.config.endpoint,t,n);return}typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&this.sendBeaconChunked(this.config.endpoint,t)}sendKeepAliveChunked(t,n,s){let i=ve(n);if(i.length<=6e4){fetch(t,{method:"POST",headers:s,body:i,keepalive:!0}).catch(()=>{});return}if(n.length<=1)return;let c=Math.ceil(n.length/2);this.sendKeepAliveChunked(t,n.slice(0,c),s),this.sendKeepAliveChunked(t,n.slice(c),s)}sendBeaconChunked(t,n){let s=ve(n);if(s.length<=6e4){navigator.sendBeacon(t,new Blob([s],{type:"application/json"}));return}if(n.length<=1)return;let i=Math.ceil(n.length/2);this.sendBeaconChunked(t,n.slice(0,i)),this.sendBeaconChunked(t,n.slice(i))}start(){this.timer||(this.timer=setInterval(()=>{this.flush().catch(()=>{})},5e3))}registerTeardown(){typeof document>"u"||(this.teardownVisibility=()=>{document.visibilityState==="hidden"&&this.beaconFlush()},this.teardownPagehide=()=>{this.beaconFlush()},document.addEventListener("visibilitychange",this.teardownVisibility),window.addEventListener("pagehide",this.teardownPagehide))}async sendBatch(t){let n=ve(t),s={"Content-Type":"application/json"};this.config.token&&(s.Authorization=`Bearer ${this.config.token}`);for(let i=0;i<=3;i++)try{let c=await fetch(this.config.endpoint,{method:"POST",headers:s,body:n});if(c.status===200||c.status===207)return;if(c.status===401){this.stopped=!0;return}if(c.status>=500&&i<3){await this.delay(1e3*2**i);continue}if(c.status===429&&i<3){let h=c.headers.get("Retry-After"),x=h?Number(h):NaN,p=Number.isFinite(x)?x*1e3:1e3*2**i;await this.delay(p);continue}return}catch{if(i<3){await this.delay(1e3*2**i);continue}return}}delay(t){return new Promise(n=>setTimeout(n,t))}};var ye={identify(){},step(){},track(){},conversion(){}},S=null,X=0;function St(){return crypto.randomUUID()}function A(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Tt(){return{widget:ye,cleanup:()=>{},config:null,captureKey:""}}function Fe(e){return e?[e.click?"1":"0",e.scroll?"1":"0",e.formField?"1":"0",e.formSubmit?"1":"0"].join(""):""}function Ue(e){if(!e)return null;let t=e.getToolResponseMetadata();if(!t)return null;let n=t._meta,s=t.waniwani??n?.waniwani,i=A(s?.endpoint);return i?{endpoint:i,token:A(s?.token),sessionId:A(s?.sessionId),source:A(s?.source)}:null}function Pe(e,t){return e?.endpoint===t?.endpoint&&e?.token===t?.token&&e?.sessionId===t?.sessionId&&e?.source===t?.source}function Et(e){let[t,n]=De(()=>Ue(e));return xe(()=>{if(!e){n(i=>i===null?i:null);return}let s=()=>{let i=Ue(e);n(c=>Pe(c,i)?c:i)};return s(),e.onToolResponseMetadataChange(()=>{s()})},[e]),t}function Rt(e,t,n){let s=e.sessionId??crypto.randomUUID(),i=crypto.randomUUID(),c=new J({endpoint:e.endpoint,token:e.token,metadata:t}),h,x=0,p=o=>{c.send(o)},m=e.source??"widget",u=Ne({sessionId:s,traceId:i,metadata:t,source:m,capture:n},p);function r(o,d){return{event_id:St(),event_type:o,timestamp:new Date().toISOString(),source:m,session_id:s,trace_id:i,user_id:h,...d}}return{captureKey:Fe(n),widget:{identify(o,d){h=o,p([r("identify",{user_id:o,user_traits:d})])},step(o,d){x++,p([r("step",{event_name:o,step_sequence:x,metadata:d})])},track(o,d){p([r("track",{event_name:o,metadata:d})])},conversion(o,d){p([r("conversion",{event_name:o,metadata:d})])}},cleanup:()=>{u(),c.stop()},config:e}}function He(e={}){let t=Ct(K),n=Et(t),s=A(e.endpoint),i=A(e.token),c=A(e.sessionId),h=Mt(()=>s?{endpoint:s,token:i??n?.token,sessionId:c??n?.sessionId,source:n?.source}:n,[s,i,c,n]),[x,p]=De(ye),m=Le(e.metadata);m.current=e.metadata;let u=Le(e.capture);u.current=e.capture;let r=Fe(e.capture);return xe(()=>(X++,()=>{X=Math.max(X-1,0),X===0&&(S?.cleanup(),S=null)}),[]),xe(()=>{if(!(typeof window>"u")){if(!h){S?.config&&(S.cleanup(),S=Tt(),p(ye));return}(!Pe(S?.config,h)||S?.captureKey!==r)&&(S?.cleanup(),S=Rt(h,m.current,u.current),p(S.widget))}},[h,r]),x}export{ee as DevModeProvider,Me as InitializeNextJsInIframe,Oe as LoadingWidget,ne as WidgetProvider,Y as detectPlatform,j as getMockState,I as initializeMockOpenAI,ke as isMCPApps,be as isOpenAI,L as updateMockDisplayMode,R as updateMockGlobal,U as updateMockTheme,N as updateMockToolOutput,oe as useCallTool,ie as useDisplayMode,re as useFlowAction,se as useIsChatGptApp,ae as useLocale,le as useMaxHeight,de as useOpenExternal,ce as useRequestDisplayMode,ue as useSafeArea,pe as useSendFollowUp,ge as useTheme,G as useToolOutput,me as useToolResponseMetadata,fe as useUpdateModelContext,He as useWaniwani,w as useWidgetClient,he as useWidgetState};
|
|
67
|
+
`})]});import{useContext as Pt,useEffect as ke,useMemo as Ht,useRef as Be,useState as je}from"react";function Lt(){return crypto.randomUUID()}function M(e,t,n){return{event_id:Lt(),event_type:t,timestamp:new Date().toISOString(),source:e.source??"widget",session_id:e.sessionId,trace_id:e.traceId,...n}}function xe(e){let t=e.trim().split(/\s+/),n=t[0]||"",i={};for(let r=1;r<t.length;r++){let u=t[r].indexOf(":");if(u===-1)continue;let f=t[r].slice(0,u),w=t[r].slice(u+1),p=Number(w);i[f]=Number.isFinite(p)&&w!==""?p:w}return{name:n,props:i}}function Pe(e){let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"}function He(e,t){let n=[],i=typeof navigator<"u"?navigator:void 0,r=i&&"connection"in i?i.connection:void 0;t([M(e,"widget_render",{metadata:{viewport_width:window.innerWidth,viewport_height:window.innerHeight,device_pixel_ratio:window.devicePixelRatio??1,touch_support:"ontouchstart"in window?1:0,connection_type:r?.effectiveType??"unknown",timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}})]);let u=s=>{t([M(e,"widget_error",{metadata:{error_message:s.message,error_stack:(s.error?.stack??"").slice(0,1024),error_source:s.filename??"unknown"}})])};window.addEventListener("error",u),n.push(()=>window.removeEventListener("error",u));let f=s=>{let o=s.reason,l=o instanceof Error?o.message:String(o),m=o instanceof Error?(o.stack??"").slice(0,1024):"";t([M(e,"widget_error",{metadata:{error_message:l,error_stack:m,error_source:"unhandledrejection"}})])};if(window.addEventListener("unhandledrejection",f),n.push(()=>window.removeEventListener("unhandledrejection",f)),e.capture?.click){let s=o=>{let l=o.target,m=l?.closest?.("[data-ww-conversion],[data-ww-step]");if(m){let d=m.getAttribute("data-ww-conversion")??m.getAttribute("data-ww-step")??"";if(xe(d).name)return}t([M(e,"widget_click",{metadata:{target_tag:l?.tagName?.toLowerCase()??"unknown",target_id:l?.id||void 0,target_class:l?.className||void 0,click_x:o.clientX,click_y:o.clientY}})])};document.addEventListener("click",s,{capture:!0}),n.push(()=>document.removeEventListener("click",s,{capture:!0}))}let w=s=>{let l=s.target?.closest?.("[data-ww-conversion]");if(!l)return;let{name:m,props:d}=xe(l.getAttribute("data-ww-conversion")||"");m&&t([M(e,"conversion",{event_name:m,metadata:Object.keys(d).length>0?d:void 0})])};document.addEventListener("click",w,{capture:!0}),n.push(()=>document.removeEventListener("click",w,{capture:!0}));let p=0,g=s=>{let l=s.target?.closest?.("[data-ww-step]");if(!l)return;let{name:m,props:d}=xe(l.getAttribute("data-ww-step")||"");m&&(p++,t([M(e,"step",{event_name:m,step_sequence:p,metadata:Object.keys(d).length>0?d:void 0})]))};document.addEventListener("click",g,{capture:!0}),n.push(()=>document.removeEventListener("click",g,{capture:!0}));let c=s=>{let o=s.target?.closest?.("a");if(!o)return;let l=o.getAttribute("href")??"",m=l.startsWith("http")&&!l.startsWith(window.location.origin);t([M(e,"widget_link_click",{metadata:{href:l,link_text:(o.textContent??"").slice(0,200),is_external:m}})])};if(document.addEventListener("click",c,{capture:!0}),n.push(()=>document.removeEventListener("click",c,{capture:!0})),e.capture?.scroll){let s=null,o=window.scrollY||0,l=()=>{s||(s=setTimeout(()=>{s=null;let m=window.scrollY||document.documentElement.scrollTop,d=document.documentElement.scrollHeight-document.documentElement.clientHeight,x=d>0?Math.round(m/d*100):0,b=m>=o?"down":"up";o=m,t([M(e,"widget_scroll",{metadata:{scroll_depth_pct:x,scroll_direction:b,viewport_height:window.innerHeight}})])},250))};window.addEventListener("scroll",l,{passive:!0}),n.push(()=>{window.removeEventListener("scroll",l),s&&clearTimeout(s)})}if(e.capture?.formField){let s=new WeakMap,o=m=>{let d=m.target;!d||!Pe(d)||s.set(d,Date.now())},l=m=>{let d=m.target;if(!d||!Pe(d))return;let x=s.get(d),b=x?Date.now()-x:0,E=d;t([M(e,"widget_form_field",{metadata:{field_name:E.name||E.id||void 0,field_type:E.type||d.tagName.toLowerCase(),time_in_field_ms:b,filled:!!E.value}})])};document.addEventListener("focusin",o,{capture:!0}),document.addEventListener("focusout",l,{capture:!0}),n.push(()=>{document.removeEventListener("focusin",o,{capture:!0}),document.removeEventListener("focusout",l,{capture:!0})})}if(e.capture?.formSubmit){let s=new WeakMap,o=m=>{let x=m.target?.closest?.("form");x&&!s.has(x)&&s.set(x,Date.now())};document.addEventListener("focusin",o,{capture:!0}),n.push(()=>document.removeEventListener("focusin",o,{capture:!0}));let l=m=>{let d=m.target,x=d?s.get(d):void 0,b=0;if(d){let E=d.querySelectorAll("input, textarea, select");for(let P of E){let O=P;(O.validity&&!O.validity.valid||O.getAttribute("aria-invalid")==="true")&&b++}}t([M(e,"widget_form_submit",{metadata:{form_id:d?.id||void 0,time_to_submit_ms:x?Date.now()-x:void 0,validation_errors:b}})])};document.addEventListener("submit",l,{capture:!0}),n.push(()=>document.removeEventListener("submit",l,{capture:!0}))}return()=>{for(let s of n)s()}}var Dt="@waniwani/sdk";function Ft(e){let n=e.event_type.startsWith("widget_")?e.event_type:`widget_${e.event_type}`,i={};e.session_id&&(i.sessionId=e.session_id),e.trace_id&&(i.traceId=e.trace_id),e.user_id&&(i.externalUserId=e.user_id);let r={...e.metadata??{}};return e.event_name&&(r.event_name=e.event_name),{id:e.event_id,type:"mcp.event",name:n,source:e.source||"widget",timestamp:e.timestamp,correlation:i,properties:r,metadata:{}}}function be(e){return JSON.stringify({sentAt:new Date().toISOString(),source:{sdk:Dt,version:"0.1.0"},events:e.map(Ft)})}var X=class{buffer=[];timer=null;flushing=!1;pendingFlush=!1;stopped=!1;config;teardownVisibility=null;teardownPagehide=null;constructor(t){this.config=t,this.start(),this.registerTeardown()}send(t){if(!this.stopped){if(this.buffer.push(...t),this.buffer.length>200){let n=this.buffer.length-200;this.buffer.splice(0,n)}this.buffer.length>=20&&this.flush().catch(()=>{})}}async flush(){if(!(this.stopped||this.buffer.length===0)){if(this.flushing){this.pendingFlush=!0;return}this.flushing=!0;try{let t=this.buffer.splice(0,20);await this.sendBatch(t)}finally{this.flushing=!1,this.pendingFlush&&this.buffer.length>0&&!this.stopped&&(this.pendingFlush=!1,this.flush().catch(()=>{}))}}}stop(){this.stopped=!0,this.timer&&(clearInterval(this.timer),this.timer=null),typeof document<"u"&&this.teardownVisibility&&(document.removeEventListener("visibilitychange",this.teardownVisibility),this.teardownVisibility=null),typeof window<"u"&&this.teardownPagehide&&(window.removeEventListener("pagehide",this.teardownPagehide),this.teardownPagehide=null)}beaconFlush(){if(this.buffer.length===0)return;let t=[...this.buffer];this.buffer.length=0;let n={"Content-Type":"application/json"};if(this.config.token&&(n.Authorization=`Bearer ${this.config.token}`),typeof fetch<"u"){this.sendKeepAliveChunked(this.config.endpoint,t,n);return}typeof navigator<"u"&&typeof navigator.sendBeacon=="function"&&this.sendBeaconChunked(this.config.endpoint,t)}sendKeepAliveChunked(t,n,i){let r=be(n);if(r.length<=6e4){fetch(t,{method:"POST",headers:i,body:r,keepalive:!0}).catch(()=>{});return}if(n.length<=1)return;let u=Math.ceil(n.length/2);this.sendKeepAliveChunked(t,n.slice(0,u),i),this.sendKeepAliveChunked(t,n.slice(u),i)}sendBeaconChunked(t,n){let i=be(n);if(i.length<=6e4){navigator.sendBeacon(t,new Blob([i],{type:"application/json"}));return}if(n.length<=1)return;let r=Math.ceil(n.length/2);this.sendBeaconChunked(t,n.slice(0,r)),this.sendBeaconChunked(t,n.slice(r))}start(){this.timer||(this.timer=setInterval(()=>{this.flush().catch(()=>{})},5e3))}registerTeardown(){typeof document>"u"||(this.teardownVisibility=()=>{document.visibilityState==="hidden"&&this.beaconFlush()},this.teardownPagehide=()=>{this.beaconFlush()},document.addEventListener("visibilitychange",this.teardownVisibility),window.addEventListener("pagehide",this.teardownPagehide))}async sendBatch(t){let n=be(t),i={"Content-Type":"application/json"};this.config.token&&(i.Authorization=`Bearer ${this.config.token}`);for(let r=0;r<=3;r++)try{let u=await fetch(this.config.endpoint,{method:"POST",headers:i,body:n});if(u.status===200||u.status===207)return;if(u.status===401){this.stopped=!0;return}if(u.status>=500&&r<3){await this.delay(1e3*2**r);continue}if(u.status===429&&r<3){let f=u.headers.get("Retry-After"),w=f?Number(f):NaN,p=Number.isFinite(w)?w*1e3:1e3*2**r;await this.delay(p);continue}return}catch{if(r<3){await this.delay(1e3*2**r);continue}return}}delay(t){return new Promise(n=>setTimeout(n,t))}};var Ce={identify(){},step(){},track(){},conversion(){}},S=null,Y=0;function Bt(){return crypto.randomUUID()}function I(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Gt(){return{widget:Ce,cleanup:()=>{},config:null,captureKey:""}}function Ke(e){return e?[e.click?"1":"0",e.scroll?"1":"0",e.formField?"1":"0",e.formSubmit?"1":"0"].join(""):""}function Ge(e){if(!e)return null;let t=e.getToolResponseMetadata();if(!t)return null;let n=t._meta,i=t.waniwani??n?.waniwani,r=I(i?.endpoint);return r?{endpoint:r,token:I(i?.token),sessionId:I(i?.sessionId),source:I(i?.source)}:null}function ze(e,t){return e?.endpoint===t?.endpoint&&e?.token===t?.token&&e?.sessionId===t?.sessionId&&e?.source===t?.source}function jt(e){let[t,n]=je(()=>Ge(e));return ke(()=>{if(!e){n(r=>r===null?r:null);return}let i=()=>{let r=Ge(e);n(u=>ze(u,r)?u:r)};return i(),e.onToolResponseMetadataChange(()=>{i()})},[e]),t}function Kt(e,t,n){let i=e.sessionId??crypto.randomUUID(),r=crypto.randomUUID(),u=new X({endpoint:e.endpoint,token:e.token,metadata:t}),f,w=0,p=o=>{u.send(o)},g=e.source??"widget",c=He({sessionId:i,traceId:r,metadata:t,source:g,capture:n},p);function s(o,l){return{event_id:Bt(),event_type:o,timestamp:new Date().toISOString(),source:g,session_id:i,trace_id:r,user_id:f,...l}}return{captureKey:Ke(n),widget:{identify(o,l){f=o,p([s("identify",{user_id:o,user_traits:l})])},step(o,l){w++,p([s("step",{event_name:o,step_sequence:w,metadata:l})])},track(o,l){p([s("track",{event_name:o,metadata:l})])},conversion(o,l){p([s("conversion",{event_name:o,metadata:l})])}},cleanup:()=>{c(),u.stop()},config:e}}function Je(e={}){let t=Pt(_),n=jt(t),i=I(e.endpoint),r=I(e.token),u=I(e.sessionId),f=Ht(()=>i?{endpoint:i,token:r??n?.token,sessionId:u??n?.sessionId,source:n?.source}:n,[i,r,u,n]),[w,p]=je(Ce),g=Be(e.metadata);g.current=e.metadata;let c=Be(e.capture);c.current=e.capture;let s=Ke(e.capture);return ke(()=>(Y++,()=>{Y=Math.max(Y-1,0),Y===0&&(S?.cleanup(),S=null)}),[]),ke(()=>{if(!(typeof window>"u")){if(!f){S?.config&&(S.cleanup(),S=Gt(),p(Ce));return}(!ze(S?.config,f)||S?.captureKey!==s)&&(S?.cleanup(),S=Kt(f,g.current,c.current),p(S.widget))}},[f,s]),w}export{ee as DevModeProvider,Ee as InitializeNextJsInIframe,Fe as LoadingWidget,ie as WidgetProvider,V as detectPlatform,j as getMockState,U as initializeMockOpenAI,Se as isMCPApps,Me as isOpenAI,oe as unstable_useSendFollowUpWithGhostGuard,L as updateMockDisplayMode,R as updateMockGlobal,D as updateMockTheme,N as updateMockToolOutput,se as useCallTool,ae as useDisplayMode,le as useFlowAction,de as useIsChatGptApp,ue as useLocale,ce as useMaxHeight,pe as useOpenExternal,ge as useRequestDisplayMode,me as useSafeArea,fe as useSendFollowUp,he as useTheme,z as useToolOutput,we as useToolResponseMetadata,ve as useUpdateModelContext,Je as useWaniwani,v as useWidgetClient,ye as useWidgetState};
|
|
68
68
|
//# sourceMappingURL=react.js.map
|