@waniwani/sdk 0.15.2 → 0.16.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 +62 -62
- package/dist/chat/embed.js.map +1 -1
- package/dist/chat/express-js/index.d.ts +17 -8
- package/dist/chat/index.d.ts +259 -0
- package/dist/chat/index.js +7 -7
- package/dist/chat/index.js.map +1 -1
- package/dist/chat/next-js/index.d.ts +17 -8
- package/dist/chunk-GYLVCP7M.js +3 -0
- package/dist/chunk-GYLVCP7M.js.map +1 -0
- package/dist/index.d.ts +88 -9
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/legacy/chat/express-js/index.d.ts +17 -8
- package/dist/legacy/chat/next-js/index.d.ts +17 -8
- package/dist/legacy/index.d.ts +39 -8
- package/dist/legacy/index.js +11 -11
- package/dist/legacy/index.js.map +1 -1
- package/dist/mcp/index.d.ts +43 -14
- package/dist/mcp/index.js +5 -5
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/react.d.ts +281 -50
- package/dist/mcp/react.js +7 -7
- package/dist/mcp/react.js.map +1 -1
- package/dist/widget-client-4MBLDRHD.js +3 -0
- package/dist/widget-client-4MBLDRHD.js.map +1 -0
- package/package.json +1 -1
package/dist/mcp/react.d.ts
CHANGED
|
@@ -642,50 +642,272 @@ declare function isOpenAI(): boolean;
|
|
|
642
642
|
*/
|
|
643
643
|
declare function isMCPApps(): boolean;
|
|
644
644
|
|
|
645
|
+
interface SearchResult {
|
|
646
|
+
source: string;
|
|
647
|
+
heading: string;
|
|
648
|
+
content: string;
|
|
649
|
+
score: number;
|
|
650
|
+
metadata?: Record<string, string>;
|
|
651
|
+
}
|
|
652
|
+
interface KbSearchTrace {
|
|
653
|
+
query: string;
|
|
654
|
+
resultCount: number;
|
|
655
|
+
results: Array<Pick<SearchResult, "source" | "heading" | "score">>;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/**
|
|
659
|
+
* Every event name in the typed taxonomy, as a runtime list. Single source of
|
|
660
|
+
* truth for {@link EventType} and for surfaces that need to recognize
|
|
661
|
+
* first-class names at runtime (the widget transport passes these through
|
|
662
|
+
* verbatim instead of namespacing them as custom widget events).
|
|
663
|
+
*/
|
|
664
|
+
declare const EVENT_TYPES: readonly ["session.started", "page.viewed", "tool.called", "quote.requested", "quote.succeeded", "quote.failed", "link.clicked", "purchase.completed", "widget_render", "user.identified", "price_shown", "prices_compared", "option_selected", "lead_qualified", "converted"];
|
|
665
|
+
type EventType = (typeof EVENT_TYPES)[number];
|
|
666
|
+
/**
|
|
667
|
+
* Properties for `page.viewed` — emitted once when the chat widget initializes
|
|
668
|
+
* on a host page (the top of the funnel). Attributed to the anonymous
|
|
669
|
+
* `visitorId` (mapped to `externalUserId`), never to a session: a page view
|
|
670
|
+
* must not create a session, otherwise sessions would equal page views and the
|
|
671
|
+
* "landed → started a conversation" funnel collapses.
|
|
672
|
+
*/
|
|
673
|
+
interface PageViewedProperties {
|
|
674
|
+
/** Full URL of the host page the widget loaded on. */
|
|
675
|
+
url?: string;
|
|
676
|
+
/** Referrer of the host page, if any. */
|
|
677
|
+
referrer?: string;
|
|
678
|
+
/** Embed mode the widget initialized in. */
|
|
679
|
+
mode?: "inline" | "floating";
|
|
680
|
+
/** Resolved device type from the visitor context. */
|
|
681
|
+
deviceType?: "mobile" | "tablet" | "desktop";
|
|
682
|
+
/** Primary browser language (BCP-47). */
|
|
683
|
+
language?: string;
|
|
684
|
+
/** IANA timezone of the visitor. */
|
|
685
|
+
timezone?: string;
|
|
686
|
+
}
|
|
687
|
+
interface ToolCalledProperties {
|
|
688
|
+
name?: string;
|
|
689
|
+
type?: "pricing" | "product_info" | "availability" | "support" | "other";
|
|
690
|
+
/** Retrieval traces for kb.search() calls made inside this tool handler. */
|
|
691
|
+
kbSearch?: KbSearchTrace[];
|
|
692
|
+
}
|
|
693
|
+
interface QuoteSucceededProperties {
|
|
694
|
+
amount?: number;
|
|
695
|
+
currency?: string;
|
|
696
|
+
}
|
|
697
|
+
interface LinkClickedProperties {
|
|
698
|
+
url?: string;
|
|
699
|
+
}
|
|
700
|
+
interface PurchaseCompletedProperties {
|
|
701
|
+
amount?: number;
|
|
702
|
+
currency?: string;
|
|
703
|
+
}
|
|
704
|
+
interface PriceShownProperties {
|
|
705
|
+
amount: number;
|
|
706
|
+
currency: string;
|
|
707
|
+
itemId?: string;
|
|
708
|
+
label?: string;
|
|
709
|
+
}
|
|
710
|
+
interface ComparedPriceOption {
|
|
711
|
+
id: string;
|
|
712
|
+
amount: number;
|
|
713
|
+
currency: string;
|
|
714
|
+
}
|
|
715
|
+
interface PricesComparedProperties {
|
|
716
|
+
options: ComparedPriceOption[];
|
|
717
|
+
}
|
|
718
|
+
interface OptionSelectedProperties {
|
|
719
|
+
id: string;
|
|
720
|
+
amount: number;
|
|
721
|
+
currency: string;
|
|
722
|
+
}
|
|
723
|
+
/**
|
|
724
|
+
* Properties for `lead_qualified` — your code declaring that a person met your
|
|
725
|
+
* qualification bar (finished the qualifying questions, requested a demo,
|
|
726
|
+
* matched your target profile). Sharing an email mid-conversation is
|
|
727
|
+
* `identify(userId, { email })`, not a qualified lead.
|
|
728
|
+
*/
|
|
729
|
+
interface LeadQualifiedProperties {
|
|
730
|
+
/**
|
|
731
|
+
* Your own lead id (e.g. the record id your lead-gen API returns). The
|
|
732
|
+
* strongest dedup key and the stable reference back to your system.
|
|
733
|
+
*/
|
|
734
|
+
externalId?: string;
|
|
735
|
+
/** The lead's email, if known. */
|
|
736
|
+
email?: string;
|
|
737
|
+
/** The lead's name, if known. */
|
|
738
|
+
name?: string;
|
|
739
|
+
}
|
|
740
|
+
interface ConvertedProperties {
|
|
741
|
+
amount: number;
|
|
742
|
+
currency: string;
|
|
743
|
+
/** When the conversion actually happened — for backdated off-platform sales. */
|
|
744
|
+
occurredAt?: string;
|
|
745
|
+
}
|
|
746
|
+
interface TrackingContext {
|
|
747
|
+
/**
|
|
748
|
+
* MCP request metadata passed through to the API.
|
|
749
|
+
*
|
|
750
|
+
* Location varies by MCP library:
|
|
751
|
+
* - `@vercel/mcp-handler`: `extra._meta`
|
|
752
|
+
* - `@modelcontextprotocol/sdk`: `request.params._meta`
|
|
753
|
+
*/
|
|
754
|
+
meta?: Record<string, unknown>;
|
|
755
|
+
/** Legacy metadata field supported for backward compatibility. */
|
|
756
|
+
metadata?: Record<string, unknown>;
|
|
757
|
+
/** Optional explicit correlation fields. */
|
|
758
|
+
sessionId?: string;
|
|
759
|
+
traceId?: string;
|
|
760
|
+
requestId?: string;
|
|
761
|
+
correlationId?: string;
|
|
762
|
+
externalUserId?: string;
|
|
763
|
+
/**
|
|
764
|
+
* Anonymous visitor id (the analytics "device id"). Counts as identity on
|
|
765
|
+
* its own: the ingest API accepts `sessionId`, `externalUserId`, or
|
|
766
|
+
* `visitorId`. The chat widget uses it for pre-session events like
|
|
767
|
+
* `page.viewed`.
|
|
768
|
+
*/
|
|
769
|
+
visitorId?: string;
|
|
770
|
+
/** Optional explicit envelope fields. */
|
|
771
|
+
eventId?: string;
|
|
772
|
+
timestamp?: string | Date;
|
|
773
|
+
source?: string;
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Modern tracking shape (preferred).
|
|
777
|
+
*/
|
|
778
|
+
interface BaseTrackEvent extends TrackingContext {
|
|
779
|
+
event: EventType;
|
|
780
|
+
properties?: Record<string, unknown>;
|
|
781
|
+
}
|
|
782
|
+
type TrackEvent = ({
|
|
783
|
+
event: "session.started";
|
|
784
|
+
} & BaseTrackEvent) | ({
|
|
785
|
+
event: "page.viewed";
|
|
786
|
+
properties?: PageViewedProperties;
|
|
787
|
+
} & BaseTrackEvent) | ({
|
|
788
|
+
event: "tool.called";
|
|
789
|
+
properties?: ToolCalledProperties;
|
|
790
|
+
} & BaseTrackEvent) | ({
|
|
791
|
+
event: "quote.requested";
|
|
792
|
+
} & BaseTrackEvent) | ({
|
|
793
|
+
event: "quote.succeeded";
|
|
794
|
+
properties?: QuoteSucceededProperties;
|
|
795
|
+
} & BaseTrackEvent) | ({
|
|
796
|
+
event: "quote.failed";
|
|
797
|
+
} & BaseTrackEvent) | ({
|
|
798
|
+
event: "link.clicked";
|
|
799
|
+
properties?: LinkClickedProperties;
|
|
800
|
+
} & BaseTrackEvent) | ({
|
|
801
|
+
event: "purchase.completed";
|
|
802
|
+
properties?: PurchaseCompletedProperties;
|
|
803
|
+
} & BaseTrackEvent) | ({
|
|
804
|
+
event: "user.identified";
|
|
805
|
+
} & BaseTrackEvent) | ({
|
|
806
|
+
event: "widget_render";
|
|
807
|
+
} & BaseTrackEvent) | ({
|
|
808
|
+
event: "price_shown";
|
|
809
|
+
properties?: PriceShownProperties;
|
|
810
|
+
} & BaseTrackEvent) | ({
|
|
811
|
+
event: "prices_compared";
|
|
812
|
+
properties?: PricesComparedProperties;
|
|
813
|
+
} & BaseTrackEvent) | ({
|
|
814
|
+
event: "option_selected";
|
|
815
|
+
properties?: OptionSelectedProperties;
|
|
816
|
+
} & BaseTrackEvent) | ({
|
|
817
|
+
event: "lead_qualified";
|
|
818
|
+
properties?: LeadQualifiedProperties;
|
|
819
|
+
} & BaseTrackEvent) | ({
|
|
820
|
+
event: "converted";
|
|
821
|
+
properties?: ConvertedProperties;
|
|
822
|
+
} & BaseTrackEvent);
|
|
823
|
+
/**
|
|
824
|
+
* Legacy tracking shape supported for existing integrations.
|
|
825
|
+
*/
|
|
826
|
+
interface LegacyTrackEvent extends TrackingContext {
|
|
827
|
+
eventType: EventType;
|
|
828
|
+
properties?: Record<string, unknown>;
|
|
829
|
+
toolName?: string;
|
|
830
|
+
toolType?: ToolCalledProperties["type"];
|
|
831
|
+
quoteAmount?: number;
|
|
832
|
+
quoteCurrency?: string;
|
|
833
|
+
linkUrl?: string;
|
|
834
|
+
purchaseAmount?: number;
|
|
835
|
+
purchaseCurrency?: string;
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* Public track input accepted by `client.track()`.
|
|
839
|
+
*/
|
|
840
|
+
type TrackInput = TrackEvent | LegacyTrackEvent;
|
|
841
|
+
interface RevenuePriceShownInput extends TrackingContext, PriceShownProperties {
|
|
842
|
+
}
|
|
843
|
+
interface RevenuePricesComparedInput extends TrackingContext, PricesComparedProperties {
|
|
844
|
+
}
|
|
845
|
+
interface RevenueOptionSelectedInput extends TrackingContext, OptionSelectedProperties {
|
|
846
|
+
}
|
|
847
|
+
/**
|
|
848
|
+
* Input for `track.leadQualified()` — identity only (`externalId`, `email`,
|
|
849
|
+
* `name`) plus the shared tracking context. There is no acquisition-source
|
|
850
|
+
* property; the envelope `source` (the origin channel) is set automatically.
|
|
851
|
+
*/
|
|
852
|
+
interface RevenueLeadQualifiedInput extends TrackingContext, LeadQualifiedProperties {
|
|
853
|
+
}
|
|
854
|
+
interface RevenueConvertedInput extends TrackingContext, ConvertedProperties {
|
|
855
|
+
}
|
|
645
856
|
/**
|
|
646
|
-
*
|
|
647
|
-
* `
|
|
648
|
-
*
|
|
649
|
-
|
|
650
|
-
|
|
857
|
+
* Revenue-oriented helpers, flat on `client.track.*` (e.g.
|
|
858
|
+
* `client.track.priceShown()`, `client.track.converted()`). Decoupled from
|
|
859
|
+
* product primitives — each maps to a typed first-class revenue event.
|
|
860
|
+
*/
|
|
861
|
+
interface RevenueTrackingApi {
|
|
862
|
+
priceShown: (input: RevenuePriceShownInput) => Promise<{
|
|
863
|
+
eventId: string;
|
|
864
|
+
}>;
|
|
865
|
+
pricesCompared: (input: RevenuePricesComparedInput) => Promise<{
|
|
866
|
+
eventId: string;
|
|
867
|
+
}>;
|
|
868
|
+
optionSelected: (input: RevenueOptionSelectedInput) => Promise<{
|
|
869
|
+
eventId: string;
|
|
870
|
+
}>;
|
|
871
|
+
leadQualified: (input?: RevenueLeadQualifiedInput) => Promise<{
|
|
872
|
+
eventId: string;
|
|
873
|
+
}>;
|
|
874
|
+
converted: (input: RevenueConvertedInput) => Promise<{
|
|
875
|
+
eventId: string;
|
|
876
|
+
}>;
|
|
877
|
+
}
|
|
878
|
+
/**
|
|
879
|
+
* `client.track` — callable for generic events (`track(event)`), with the
|
|
880
|
+
* revenue helpers attached flat: `track.priceShown()`, `track.leadQualified()`,
|
|
881
|
+
* `track.converted()`, etc.
|
|
651
882
|
*/
|
|
652
|
-
interface
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
formSubmit?: boolean;
|
|
883
|
+
interface TrackFn extends RevenueTrackingApi {
|
|
884
|
+
(event: TrackInput): Promise<{
|
|
885
|
+
eventId: string;
|
|
886
|
+
}>;
|
|
657
887
|
}
|
|
658
888
|
|
|
659
889
|
interface BaseUseWaniwaniOptions {
|
|
660
890
|
/**
|
|
661
891
|
* JWT widget token for authenticating directly with the Waniwani backend.
|
|
662
892
|
* If omitted, the hook resolves from tool response metadata
|
|
663
|
-
* (`
|
|
893
|
+
* (`_meta["waniwani/widget"].token`).
|
|
664
894
|
*/
|
|
665
895
|
token?: string;
|
|
666
896
|
/**
|
|
667
897
|
* Session ID to use for event correlation.
|
|
668
898
|
* If omitted, the hook resolves from tool response metadata
|
|
669
|
-
* (`
|
|
899
|
+
* (`_meta["waniwani/widget"].sessionId`), then falls back to a random UUID
|
|
900
|
+
* so the widget's own events still group together.
|
|
670
901
|
*/
|
|
671
902
|
sessionId?: string;
|
|
672
903
|
/**
|
|
673
|
-
* Additional
|
|
904
|
+
* Additional fields merged into every tracked event's envelope metadata.
|
|
674
905
|
*/
|
|
675
906
|
metadata?: Record<string, unknown>;
|
|
676
|
-
/**
|
|
677
|
-
* Opt-in toggles for noisy auto-capture event types. Default: all off.
|
|
678
|
-
* Always-on capture: widget_render, widget_error, widget_link_click,
|
|
679
|
-
* `data-ww-step` / `data-ww-conversion` clicks.
|
|
680
|
-
*
|
|
681
|
-
* @example
|
|
682
|
-
* useWaniwani({ capture: { click: true, scroll: true } });
|
|
683
|
-
*/
|
|
684
|
-
capture?: AutoCaptureToggles;
|
|
685
907
|
}
|
|
686
908
|
/**
|
|
687
|
-
* Context-driven options: `endpoint` and `source` are resolved from
|
|
688
|
-
* `
|
|
909
|
+
* Context-driven options: `endpoint` and `source` are resolved from the
|
|
910
|
+
* widget host (tool response `_meta["waniwani/widget"]`). `source` may be
|
|
689
911
|
* overridden explicitly.
|
|
690
912
|
*/
|
|
691
913
|
interface ContextDrivenOptions extends BaseUseWaniwaniOptions {
|
|
@@ -704,8 +926,8 @@ interface ExplicitEndpointOptions extends BaseUseWaniwaniOptions {
|
|
|
704
926
|
source: string;
|
|
705
927
|
}
|
|
706
928
|
/**
|
|
707
|
-
* Options for the useWaniwani hook. Either rely on
|
|
708
|
-
*
|
|
929
|
+
* Options for the useWaniwani hook. Either rely on the widget host
|
|
930
|
+
* (omit `endpoint`) or pass `endpoint` + `source` explicitly.
|
|
709
931
|
*/
|
|
710
932
|
type UseWaniwaniOptions = ContextDrivenOptions | ExplicitEndpointOptions;
|
|
711
933
|
/**
|
|
@@ -714,44 +936,53 @@ type UseWaniwaniOptions = ContextDrivenOptions | ExplicitEndpointOptions;
|
|
|
714
936
|
interface WaniwaniWidget {
|
|
715
937
|
/**
|
|
716
938
|
* The session ID stamped on every event this widget emits, so hosts can
|
|
717
|
-
* correlate widget activity with server-side tracking
|
|
718
|
-
* the internal `_meta` shape.
|
|
939
|
+
* correlate widget activity with server-side tracking.
|
|
719
940
|
*
|
|
720
|
-
* Resolved from (1) the explicit `sessionId` option, (2)
|
|
721
|
-
* `
|
|
722
|
-
* on mount. `undefined` until the widget initializes
|
|
723
|
-
*
|
|
941
|
+
* Resolved from (1) the explicit `sessionId` option, (2) the widget config
|
|
942
|
+
* injected by `withWaniwani` (`_meta["waniwani/widget"].sessionId`), else a
|
|
943
|
+
* random UUID generated on mount. `undefined` until the widget initializes
|
|
944
|
+
* and when no config resolves (no-op widget).
|
|
724
945
|
*/
|
|
725
946
|
readonly sessionId?: string;
|
|
726
|
-
/**
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
947
|
+
/**
|
|
948
|
+
* Track a typed event. The exact same surface as the server client:
|
|
949
|
+
* `track({ event: "quote.succeeded", properties })`,
|
|
950
|
+
* `track.priceShown({ amount, currency })`, `track.converted({ ... })`.
|
|
951
|
+
* Identity (session, trace, user) is stamped automatically.
|
|
952
|
+
*/
|
|
953
|
+
track: TrackFn;
|
|
954
|
+
/** Tie all subsequent widget events to this user (emits `user.identified`). */
|
|
955
|
+
identify(userId: string, traits?: Record<string, unknown>): Promise<{
|
|
956
|
+
eventId: string;
|
|
957
|
+
}>;
|
|
958
|
+
/** Flush buffered events immediately instead of waiting for the timer. */
|
|
959
|
+
flush(): Promise<void>;
|
|
734
960
|
}
|
|
735
961
|
/**
|
|
736
|
-
* React hook for
|
|
737
|
-
*
|
|
738
|
-
*
|
|
739
|
-
* interactions) and provides manual tracking methods. Returns a singleton
|
|
740
|
-
* instance shared across all consumers.
|
|
962
|
+
* React hook for tracking from inside an MCP-app widget. Returns the same
|
|
963
|
+
* `track` surface as the server client, with session identity stamped
|
|
964
|
+
* automatically from the config `withWaniwani` injects into tool responses.
|
|
741
965
|
*
|
|
742
966
|
* Config resolution order:
|
|
743
967
|
* 1. Explicit `endpoint` / `token` / `sessionId` / `source` options
|
|
744
|
-
* 2. `
|
|
968
|
+
* 2. Tool response `_meta["waniwani/widget"]` via the widget host bridge
|
|
969
|
+
* (with or without the legacy `WidgetProvider`)
|
|
745
970
|
* 3. No-op if `endpoint` cannot be resolved or `source` is unknown
|
|
746
971
|
*
|
|
747
972
|
* @example
|
|
748
973
|
* ```tsx
|
|
749
974
|
* function MyWidget() {
|
|
750
975
|
* const wani = useWaniwani();
|
|
751
|
-
* //
|
|
752
|
-
*
|
|
753
|
-
*
|
|
754
|
-
*
|
|
976
|
+
* // wani.sessionId correlates with server-side tracking
|
|
977
|
+
* return (
|
|
978
|
+
* <button
|
|
979
|
+
* onClick={() =>
|
|
980
|
+
* wani.track.optionSelected({ id: "pro", amount: 49, currency: "EUR" })
|
|
981
|
+
* }
|
|
982
|
+
* >
|
|
983
|
+
* Choose Pro
|
|
984
|
+
* </button>
|
|
985
|
+
* );
|
|
755
986
|
* }
|
|
756
987
|
* ```
|
|
757
988
|
*/
|
package/dist/mcp/react.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{a as
|
|
2
|
+
import{a as K,b as Me,c as Ce}from"../chunk-DP6SAQTK.js";import{b as L,c as Ee}from"../chunk-RZKVTH7F.js";import{a as Re}from"../chunk-GYLVCP7M.js";import{Fragment as ft,jsx as P,jsxs as gt}from"react/jsx-runtime";function ct(){let e=window.innerBaseUrl,t=window.__wwPassthroughOrigins??[],n=document.documentElement;new MutationObserver(p=>{p.forEach(f=>{if(f.type==="attributes"&&f.target===n){let d=f.attributeName;d&&d!=="suppresshydrationwarning"&&d!=="lang"&&d!=="class"&&d!=="style"&&n.removeAttribute(d)}})}).observe(n,{attributes:!0,attributeOldValue:!0});let o=history.replaceState.bind(history);history.replaceState=(p,f,d)=>{try{let u=new URL(String(d??""),window.location.href);o(null,f,u.pathname+u.search+u.hash)}catch{}};let i=history.pushState.bind(history);history.pushState=(p,f,d)=>{try{let u=new URL(String(d??""),window.location.href);i(null,f,u.pathname+u.search+u.hash)}catch{}};let a=new URL(e).origin,l=window.self!==window.top;if(window.addEventListener("click",p=>{let f=p?.target?.closest("a");if(!f||!f.href)return;let d=new URL(f.href,window.location.href);if(d.origin!==window.location.origin&&d.origin!==a)try{window.openai&&(window.openai?.openExternal({href:f.href}),p.preventDefault())}catch{console.warn("openExternal failed, likely not in OpenAI client")}},!0),l&&window.location.origin!==a){let p=window.fetch;window.fetch=((c,y)=>{let x=typeof c=="string"&&!/^[a-z][a-z0-9+.-]*:/i.test(c)&&!c.startsWith("//"),w;if(typeof c=="string"||c instanceof URL?w=new URL(c,window.location.href):w=new URL(c.url,window.location.href),w.origin===a)return typeof c=="string"||c instanceof URL?c=w.toString():c=new Request(w.toString(),c),p.call(window,c,{...y,mode:"cors"});if(t.indexOf(w.origin)!==-1)return p.call(window,c,y);if(x&&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,c=w.toString(),p.call(window,c,{...y,mode:"cors"})}return p.call(window,c,y)});let f=a.replace(/^http/,"ws"),d=window.WebSocket,u=((c,y)=>{let x=new URL(String(c),window.location.href);if(x.origin===window.location.origin||x.origin===window.location.origin.replace(/^http/,"ws")){let w=new URL(f);return w.pathname=x.pathname,w.search=x.search,w.hash=x.hash,new d(w.toString(),y)}return new d(c,y)});u.prototype=d.prototype,Object.assign(u,{CONNECTING:d.CONNECTING,OPEN:d.OPEN,CLOSING:d.CLOSING,CLOSED:d.CLOSED}),window.WebSocket=u}}var pt=`(${ct.toString()})()`;function Ue({baseUrl:e,passthroughOrigins:t}){return gt(ft,{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:pt})]})}import{useCallback as S,useEffect as N,useRef as Z,useState as k}from"react";var Oe={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},B={...Oe};function O(e){typeof window>"u"||window.openai||(B={...Oe,toolOutput:e??null},window.openai={...B,requestDisplayMode:async({mode:t})=>(I("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=>{I("widgetState",t)}},window.dispatchEvent(new L({globals:B})))}function I(e,t){typeof window>"u"||!window.openai||(B[e]=t,window.openai[e]=t,window.dispatchEvent(new L({globals:{[e]:t}})))}function G(){return{...B}}function W(e){I("toolOutput",e)}function A(e){I("displayMode",e)}function D(e){I("theme",e)}import{Fragment as Q,jsx as s,jsxs as h}from"react/jsx-runtime";var q=150;function We({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 mt({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 ht({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 wt({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 yt({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 vt({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 xt({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 bt({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 kt=`
|
|
3
3
|
@keyframes devPanelSlideIn {
|
|
4
4
|
0% {
|
|
5
5
|
opacity: 0;
|
|
@@ -47,22 +47,22 @@ import{a as V,b as ke,c as Ce}from"../chunk-DP6SAQTK.js";import{b as H,c as Me}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[r,o]=k(!1),[i,a]=k(!1);return N(()=>{if(new URLSearchParams(window.location.search).get("platform")==="mcp-apps"){o(!0);return}if(t&&t.length>0){let p=window.location.pathname,f=t.some(d=>p===d||p.startsWith(`${d}/`));a(f),f&&O(e)}else O(e),a(!0);o(!0)},[e,t]),r?i?h(Q,{children:[s(St,{children:n}),s(Tt,{defaultProps:e})]}):s(Q,{children:n}):null}function St({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 Ae({options:e,value:t,onChange:n}){let r=e.findIndex(o=>o.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(${r*100}% + ${r*2}px))`,background:"rgba(255, 255, 255, 0.1)"}}),e.map(o=>h("button",{type:"button",onClick:()=>n(o.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===o.value?"text-white":"text-gray-400 hover:text-gray-300"}
|
|
54
|
+
`,children:[o.icon,s("span",{className:"capitalize",children:o.label})]},o.value))]})}function Tt({defaultProps:e}){let[t,n]=k(()=>typeof window>"u"?!1:localStorage.getItem("dev-controls-open")==="true"),[r,o]=k(!1),[i,a]=k(t),[l,p]=k("inline"),[f,d]=k("dark"),[u,c]=k(!1),[y,x]=k(()=>JSON.stringify(e??{},null,2)),[w,T]=k(null),_=Z(null),rt=Z(null),J=Z(null);N(()=>{let g=G();p(g.displayMode),d(g.theme)},[]),N(()=>{typeof window>"u"||(window.openai||(window.openai={}),window.openai.safeArea={insets:{top:0,bottom:u?q:0,left:0,right:0}},window.dispatchEvent(new L({globals:{safeArea:window.openai.safeArea}})))},[u]),N(()=>{localStorage.setItem("dev-controls-open",String(t))},[t]);let Ie=S(()=>{a(!0),requestAnimationFrame(()=>{n(!0)})},[]),C=S(()=>{o(!0),n(!1),setTimeout(()=>{a(!1),o(!1)},150)},[]),X=S(()=>{t?C():Ie()},[t,Ie,C]);N(()=>{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]),N(()=>{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 ot=S(g=>{p(g),A(g)},[]),it=S(g=>{d(g),D(g)},[]),j=S(g=>{try{let b=JSON.parse(g);T(null),W(b)}catch{T("Invalid JSON")}},[]),st=S(g=>{x(g),_.current&&clearTimeout(_.current),_.current=setTimeout(()=>{j(g)},500)},[j]),at=S(()=>{_.current&&clearTimeout(_.current),j(y)},[j,y]),lt=S(()=>{let g=JSON.stringify(e??{},null,2);x(g),T(null),W(e??{}),p("inline"),A("inline"),d("dark"),D("dark")},[e]),dt=[{value:"inline",label:"inline",icon:s(ht,{className:"w-3.5 h-3.5"})},{value:"pip",label:"pip",icon:s(wt,{className:"w-3.5 h-3.5"})},{value:"fullscreen",label:"full",icon:s(yt,{className:"w-3.5 h-3.5"})}],ut=[{value:"light",label:"light",icon:s(vt,{className:"w-3.5 h-3.5"})},{value:"dark",label:"dark",icon:s(xt,{className:"w-3.5 h-3.5"})}];return h(Q,{children:[s("style",{dangerouslySetInnerHTML:{__html:kt}}),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:[
|
|
58
|
+
`},"aria-label":"Toggle Dev Controls","aria-expanded":t,children:[s(We,{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:rt,className:`absolute bottom-14 right-0 w-80 ${t&&!r?"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:[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:[l(Ee,{className:"w-4 h-4 text-gray-400"}),l("span",{className:"text-sm font-medium text-white",children:"Dev Controls"})]}),y("div",{className:"flex items-center gap-2",children:[l("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"}),l("button",{type:"button",onClick:W,className:"p-1 rounded-md text-gray-500 hover:text-gray-300 hover:bg-white/5 transition-colors",children:l(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:[l("label",{htmlFor:"display-mode",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Display Mode"}),l(Re,{options:Ze,value:h,onChange:Ve})]}),y("div",{children:[l("label",{htmlFor:"theme",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Theme"}),l(Re,{options:Qe,value:g,onChange:$e})]}),y("div",{children:[l("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:[l("span",{children:"Mock ChatGPT Input Bar"}),l("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:[l("label",{htmlFor:"widget-props",className:"text-[11px] font-medium uppercase tracking-wider text-gray-500 block mb-2",children:"Widget Props"}),l("textarea",{value:a,onChange:w=>Xe(w.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:w=>{d||(w.target.style.borderColor="rgba(99, 102, 241, 0.5)")},onBlurCapture:w=>{d||(w.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:[l("svg",{"aria-hidden":"true","aria-label":"Error",className:"w-3 h-3",viewBox:"0 0 16 16",fill:"currentColor",children:l("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:w=>{w.currentTarget.style.background="rgba(255, 255, 255, 0.08)",w.currentTarget.style.borderColor="rgba(255, 255, 255, 0.1)"},onMouseLeave:w=>{w.currentTarget.style.background="rgba(255, 255, 255, 0.04)",w.currentTarget.style.borderColor="rgba(255, 255, 255, 0.06)"},children:[l(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:[l("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:l("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:l("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),l("div",{className:"flex-1 text-gray-400 text-sm",children:"Ask me anything..."}),l("div",{className:"w-8 h-8 rounded-full bg-[#424242] flex items-center justify-center",children:l("svg",{"aria-hidden":"true",className:"w-4 h-4 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:l("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 We}from"react";import{createContext as mt}from"react";var _=mt(null);import{Fragment as _e,jsx as te}from"react/jsx-runtime";var yt="waniwani:send-follow-up:advanced:",xt=1e4;function Ae(e){return`${yt}${e??"default"}`}function bt(e){try{let t=globalThis.localStorage?.getItem(Ae(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(Ae(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=We(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,h=We("");h.current===""&&(h.current=crypto.randomUUID());let p=ft((c,s)=>{ne()&&kt(f,h.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=h.current;return function({children:o}){if(!ne())return te(_e,{children:o});let a=bt(f);return a&&a.byMountId!==c&&Date.now()-a.at<xt?te(Mt,{}):te(_e,{children:o})}},[f]);return{sendFollowUp:p,Guard:g}}import{useCallback as Et}from"react";import K,{useCallback as Oe,useContext as St,useEffect as Ue,useState as re,useSyncExternalStore as Tt}from"react";async function Ie(){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[i,r]=re(null),[u,f]=re(null),[h,p]=re(!0);return Ue(()=>{let g=!0,c=null;async function s(){try{let o=await Ie();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()}},[]),Ue(()=>{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)):h||!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=Oe(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=Oe(()=>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()=>{Me(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 h=typeof u=="function"?u(f):u;return V()==="openai"&&h!=null&&window.openai?.setWidgetState(h),h})},[]);return[n,r]}import{jsx as A,jsxs as Ne}from"react/jsx-runtime";var Le=()=>Ne("div",{className:"flex flex-col items-center justify-center h-full min-h-[120px] gap-4",children:[Ne("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:`
|
|
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:`
|
|
63
63
|
@keyframes shimmer {
|
|
64
64
|
0% { background-position: 200% 0; }
|
|
65
65
|
100% { background-position: -200% 0; }
|
|
66
66
|
}
|
|
67
|
-
`})]});import{useContext as Pt,useEffect as Ge,useMemo as Ht,useRef as Pe,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,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),h=t[r].slice(u+1),p=Number(h);i[f]=Number.isFinite(p)&&h!==""?p:h}return{name:n,props:i}}function De(e){let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"}function Fe(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,a=o instanceof Error?o.message:String(o),m=o instanceof Error?(o.stack??"").slice(0,1024):"";t([M(e,"widget_error",{metadata:{error_message:a,error_stack:m,error_source:"unhandledrejection"}})])};if(window.addEventListener("unhandledrejection",f),n.push(()=>window.removeEventListener("unhandledrejection",f)),e.capture?.click){let s=o=>{let a=o.target,m=a?.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:a?.tagName?.toLowerCase()??"unknown",target_id:a?.id||void 0,target_class:a?.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 h=s=>{let a=s.target?.closest?.("[data-ww-conversion]");if(!a)return;let{name:m,props:d}=xe(a.getAttribute("data-ww-conversion")||"");m&&t([M(e,"conversion",{event_name:m,metadata:Object.keys(d).length>0?d:void 0})])};document.addEventListener("click",h,{capture:!0}),n.push(()=>document.removeEventListener("click",h,{capture:!0}));let p=0,g=s=>{let a=s.target?.closest?.("[data-ww-step]");if(!a)return;let{name:m,props:d}=xe(a.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 a=o.getAttribute("href")??"",m=a.startsWith("http")&&!a.startsWith(window.location.origin);t([M(e,"widget_link_click",{metadata:{href:a,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,a=()=>{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",a,{passive:!0}),n.push(()=>{window.removeEventListener("scroll",a),s&&clearTimeout(s)})}if(e.capture?.formField){let s=new WeakMap,o=m=>{let d=m.target;!d||!De(d)||s.set(d,Date.now())},a=m=>{let d=m.target;if(!d||!De(d))return;let x=s.get(d),b=x?Date.now()-x:0,T=d;t([M(e,"widget_form_field",{metadata:{field_name:T.name||T.id||void 0,field_type:T.type||d.tagName.toLowerCase(),time_in_field_ms:b,filled:!!T.value}})])};document.addEventListener("focusin",o,{capture:!0}),document.addEventListener("focusout",a,{capture:!0}),n.push(()=>{document.removeEventListener("focusin",o,{capture:!0}),document.removeEventListener("focusout",a,{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 a=m=>{let d=m.target,x=d?s.get(d):void 0,b=0;if(d){let T=d.querySelectorAll("input, textarea, select");for(let P of T){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",a,{capture:!0}),n.push(()=>document.removeEventListener("submit",a,{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,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"),h=f?Number(f):NaN,p=Number.isFinite(h)?h*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 He={sessionId:void 0,identify(){},step(){},track(){},conversion(){}},I=null,Y=0;function Bt(){return crypto.randomUUID()}function R(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Ke(e){return e?[e.click?"1":"0",e.scroll?"1":"0",e.formField?"1":"0",e.formSubmit?"1":"0"].join(""):""}function Be(e){if(!e)return null;let t=e.getToolResponseMetadata();if(!t)return null;let n=t._meta,i=t.waniwani??n?.waniwani,r=R(i?.endpoint);return r?{endpoint:r,token:R(i?.token),sessionId:R(i?.sessionId),source:R(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 Gt(e){let[t,n]=je(()=>Be(e));return Ge(()=>{if(!e){n(r=>r===null?r:null);return}let i=()=>{let r=Be(e);n(u=>ze(u,r)?u:r)};return i(),e.onToolResponseMetadataChange(()=>{i()})},[e]),t}function jt(e,t,n){let i=e.sessionId??crypto.randomUUID(),r=crypto.randomUUID(),u=new X({endpoint:e.endpoint,token:e.token,metadata:t}),f,h=0,p=o=>{u.send(o)},g=e.source,c=Fe({sessionId:i,traceId:r,metadata:t,source:g,capture:n},p);function s(o,a){return{event_id:Bt(),event_type:o,timestamp:new Date().toISOString(),source:g,session_id:i,trace_id:r,user_id:f,...a}}return{captureKey:Ke(n),widget:{sessionId:i,identify(o,a){f=o,p([s("identify",{user_id:o,user_traits:a})])},step(o,a){h++,p([s("step",{event_name:o,step_sequence:h,metadata:a})])},track(o,a){p([s("track",{event_name:o,metadata:a})])},conversion(o,a){p([s("conversion",{event_name:o,metadata:a})])}},cleanup:()=>{c(),u.stop()},config:e}}function Je(e={}){let t=Pt(_),n=Gt(t),i=R(e.endpoint),r=R(e.token),u=R(e.sessionId),f=R(e.source),h=Ht(()=>{let a=f??n?.source;return a?i?{endpoint:i,token:r??n?.token,sessionId:u??n?.sessionId,source:a}:n?{...n,source:a}:null:null},[i,r,u,f,n]),[p,g]=je(He),c=Pe(e.metadata);c.current=e.metadata;let s=Pe(e.capture);s.current=e.capture;let o=Ke(e.capture);return Ge(()=>{if(!(typeof window>"u")){if(!h){g(He);return}return(!ze(I?.config,h)||I?.captureKey!==o)&&(I?.cleanup(),I=jt(h,c.current,s.current)),g(I.widget),Y++,()=>{Y=Math.max(Y-1,0),Y===0&&(I?.cleanup(),I=null)}}},[h,o]),p}export{ee as DevModeProvider,Se as InitializeNextJsInIframe,Le as LoadingWidget,ie as WidgetProvider,V as detectPlatform,j as getMockState,U as initializeMockOpenAI,Ce as isMCPApps,ke as isOpenAI,oe as unstable_useSendFollowUpWithGhostGuard,L as updateMockDisplayMode,E 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};
|
|
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};
|
|
68
68
|
//# sourceMappingURL=react.js.map
|